Reputation: 21
name = input('Enter your name please: ')
while name != str:
name = input('Please enter only letters for your name: ')
ss = input('Enter your Social Security Number: ')
while ss != int:
ss = input('Please enter only numbers for your social security number:')
So I have this basic program that asks the user for his name and SS# and I wanted to do so the user can't input a str or a float where he is supposed to input an int. I tried this but it'll just loop forever because the If statement is checking to see if the input is the data type str or int, How can I do it to check if the variable is an int or a str?
Upvotes: 1
Views: 124
Reputation: 5948
You're trying to compare the value with a type
. You should instead store the name and check if has only letters (.isalpha()
) and try a type casting on the security number. If it fails, it's not a valid input. Using isnumeric()
for the SSN is also an option. Something like:
name = input('Enter your name please: ')
while not name.isalpha():
name = input('Please enter only letters for your name: ')
ss = input('Enter your Social Security Number: ')
try:
int(ss)
valid_ss = True
except ValueError:
valid_ss = False
while not valid_ss:
ss = input('Please enter only numbers for your social security number:')
try:
int(ss)
valid_ss = True
except ValueError:
valid_ss = False
or
name = input('Enter your name please: ')
while not name.isalpha():
name = input('Please enter only letters for your name: ')
ss = input('Enter your Social Security Number: ')
while not ss.isnumeric():
ss = input('Please enter only numbers for your social security number:')
Upvotes: 3
Reputation: 1857
name != str
does not do what you think it does. The result of input() is always a string. If you only want to get certain types of strings, then you have to validate them yourself. For checking if something only contains letters or only contains numbers you can use name.isalpha()
and name.isnumeric()
.
If you need something more complicated than what these or othe other builtin string methods provide, then you'll probably need to write a regular expression or other custom validation code.
Upvotes: 2