Reputation: 31
I'm as new as it gets to programming. I have a question. Once the user has selected option 1-6, they are required to input the numbers they want to calculate, how do I stop the user from inputting a character instead of a number?
while menu:
usersChoice=raw_input("Please make your selection now:")
if usersChoice=="1":
print("You have selected AREA (SQUARE)")
length=input("Input Length?")
print"Area is:", length**2.0
if usersChoice=="2":
print("You have selected AREA (Rectangle)")
length=input("Input Length?")
width=input("Input Width?")
print("Area is:", length*width)
menu=False
Upvotes: 3
Views: 83
Reputation: 1033
You could use str.isalpha()
to detect characters.
Ex:
usersChoice=raw_input("Please make your selection now:")
if usersChoice.isalpha() == True:
print("Sorry, your input must only be numerical. Please try again.")
menu()
Upvotes: 0
Reputation:
you have some errors
*from the first IF cond you are forget open and close bracet for print method
* the varable raw_input is not define into a programm !
* you write true loop forever print this things
corect your error
Upvotes: 1
Reputation: 92440
Strings in Python have an isdigit()
function.
You can use it to test:
"123".isdigit() #True
"a123".isdigit() #False
This only tests for positive integers, however. So:
"12.5".isdigit() #False
"-20".isdigit() #False
Upvotes: 1
Reputation: 601
Try this code:
def validate_is_number(number):
try:
float(number)
return True
except ValueError:
return False
validate_is_number(usersChoice)
You can the use the results of validate_is_number with an if statement to print back and ask for another response.
Upvotes: 1