'input in python to be only in string
I am a beginner in Python so kindly do not use complex or advanced code.
I have three if conditions to which I want certain responses, and I want my code to give only one response.
First I want the input to only answer in string not in integer or float
f = input("Please enter your name :")it should give an error if an integer or float is given
if type (f)== int or float : print("Invalid entry")if f=="" : print("Invalid input. Your name cannot be blank. ")
I have already tried
f = str(input("Please enter your name :"))
it is not working my code still accepts the ans in integer and string.
If I give the string input it gives me the following response:
if type (f)== int or float :
print("Invalid entry")
I am a beginner so I might have made a lot of mistakes. Your patience would be appreciated.
Solution 1:[1]
input() always returns a string, so you can try these methods:
METHOD 1. Use isalpha(). It checks if all characters are alphabetical, but does not allow for spaces.
name = input('Please enter your name: ')
if name.isalpha() == False:
print('Please enter a alphabetical name')
To allow spaces in a name (for example, first and last name), do this:
name = input('Please enter your name: ')
nospacename = name.replace(' ','')
if nospacename.isalpha() == False:
print('Please enter a alphabetical name')
This does not change the value of name, however.
METHOD 2. Try to convert it to a integer or float, and print the message if it is possible. Otherwise, do nothing.
name = input('Please enter your name: ')
try:
intname = int(name)
floatname = float(name)
print('Please enter an alphabetical name.')
except:
pass
METHOD 3. Go through the name, character by character, and check if it is a type int (integer) or float.
name = input('Please enter your name: ')
namelist = list(name)
invalid = 0
for i in range(len(name)):
if type(namelist[i]) == int:
invalid = invalid + 1
elif type(namelist[i]) == float:
invalid = invalid + 1
else:
pass
if invalid > 0:
print('Please enter a alphabetical name.')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Python |
