How to make Python to check is variable a number or letter?
I’m a Python beginner, and I need help figuring out how to check whether user input is a number or not. In my code, I want to allow the user to input their age, and if they input a valid number, the program should continue. However, if they input something that isn’t a number, I want the program to notify them and ask them to try again. Here’s a part of my code:
if age == int or float:
print("Ok, we’re done with the basic info! Would you like us to compile and show your details? YES or NO?")
elif age == False:
print("Hey, that's not a number... Try again!")
How can I properly check the input type and handle both cases?
Answer:
No problem with the Serbian print statements! To check whether the user’s input is a number or not, you can use Python’s str.isdigit()
method for checking if a string contains only digits. You can also use try-except
to handle numbers more robustly, especially if you’re dealing with floats. Here’s how you can modify your code:
age = input("Unesite godine: ")
# Try converting the input to a number
try:
age = float(age) # You can use int() if you want whole numbers only
print("Ok, zavrsili smo sa osnovnim informacijama! Da li zelite da ih uklopimo i pokazemo Vase osnovne informacije? DA ili NE?")
except ValueError:
print("Hej, to nije broj... Pokusaj ponovo")