Jodi
Jodi

Reputation: 31

How do I get my program to loop if a character is entered instead of a number

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

Answers (4)

Vale
Vale

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

user4509170
user4509170

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

Mark
Mark

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

Kerry Hatcher
Kerry Hatcher

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

Related Questions