Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialMichael Aguilar
3,866 Pointswhat if I enter a number when asked for a name? and vice versa?
What if I do this:
"what is your name? :" and I enter '45'
how can I show a message asking the user to enter a valid form of input, in this case, the answer in the format of letters only?
1 Answer
Maxwell Newberry
7,693 PointsYou can use a lesson we learned regarding Try
and except ValueError
. We know that the default variable type when we receive a prompt is string
. So what we can do is take in that string, then try to convert it to an integer. If it contains a period (.
) we can check it for a float as well. If the input does not properly convert, we will raise a ValueError exception and know that it is in fact a string and non-numeric.
user_input = input ("Enter input value")
try:
if "." in user_input :
val = float(user_input)
print(val, "Yes, user input is a float number.")
else:
val = int(user_input)
print(val, "Yes, input string is an Integer.")
except ValueError:
print("No.. the input string is not a number. It's a string")
The issue with this method is that you cannot check whether the input is Maxwell45, because that will return that it is a string.
Michael Aguilar
3,866 PointsMichael Aguilar
3,866 PointsI realized I was getting ahead of myself lol. The following videos touched on the question I had. Still, your answer helps understanding it even more, thank you!