Beginner here. Thank you for the downvotes already <3
i have been wondering this for a longer time If i check for user input, i know how to check for strings. But what if i want to check if the user has entered just integers or floats. I tried it with an "if name == int or float: block but of course that didn't work. Can you help me out? How do i check for that? Here is my code. Of course the input i always converted to a string so i don't know how to do that.
print("Enter a name: ")
while True:
name = input()
if name != "":
print("Thank you for entering a name: ")
break
else:
print("Please enter a name: ")
i also tried this:
print("Enter a name: ")
while True:
name = input()
if type(name) != int:
print("Thats not a name!")
print("Now please enter a name without numbers")
elif type(name) != float:
print("Thats also not a name!")
print("Now please enter a name without numbers")
elif type(name) != "":
print("Thank you for entering your name!")
break
else:
print("Please enter a name: ")
CodePudding user response:
As far as I know, the answer to this is probably this instead.
print("Enter a name: ")
while True:
name = input()
if type(name) != int:
print("Thank you for entering a name: ")
break
else:
print("Please enter a name: ")
Also I can understand why you did that.
The previous code you created meant that if the user typed the class int. This will be impossible to type a class because input()
only takes a string from the user's input.
CodePudding user response:
For int
you can use the isnumeric()
method
"1".isnumeric() #True
For float
, you should try if casting to float is possible
def isFloat(num):
try:
float(num)
return True
except ValueError:
return False
Now use both these methods :
print("Enter a name: ")
while True:
name = input()
if name.isnumeric() or isFloat(name):
print("Thats not a name!")
print("Now please enter a name without numbers")
elif type(name) != "":
print("Thank you for entering your name!")
break
else:
print("Please enter a name: ")
Output :
Enter a name:
1
Thats not a name!
Now please enter a name without numbers
1.2
Thats not a name!
Now please enter a name without numbers
abc
Thank you for entering your name!