Home > Blockchain >  Trying to get my code to input only digit values and if it inputs a non digit value it prints You ha
Trying to get my code to input only digit values and if it inputs a non digit value it prints You ha

Time:11-28

menu()
selection=float(input("Select a menu- Input a number:"))
if selection==1:
    print("::menu 1::")
elif selection==2:
    print("::menu 2::")
elif selection==3:
    print("::menu 3::")
elif selection==4:
    exit
elif selection<=0 or selection>4:
    print("There is no menu",end=" ")
    print(selection)
else:
    print("You have input a non digit value. Select again:")

it seems to only recognise decimals as non digit value but if i wear to write a word it would say could not convert string to float-How do i fix this im new to programming

CodePudding user response:

Try this

selection=input("Select a menu- Input a number:")
if not selection.isdigit():
    print("You have input a non digit value. Select again:")
else:
    selection = float(selection)
    if selection==1:
        print("::menu 1::")
    elif selection==2:
        print("::menu 2::")
    elif selection==3:
        print("::menu 3::")
    elif selection==4:
        exit
    elif selection<=0 or selection>4:
        print("There is no menu",end=" ")
        print(selection)

CodePudding user response:

I've made a few changes to your code and added a few comments inline

# We start with None so that it enters the loop at least once
selection = None


# We create loop to keep asking the question until the user provides a number
while not selection:
    selection=input("Select a menu- Input a number:")
    # Check if the number is a decimal
    if selection.isdecimal():
        # I convert to an int since it's more natural
        selection = int(selection)
        # At this point, it will exit the loop
    else:
        # The user has intereed an incorrect value. 
        print("You have input a non integer value. Select again:")
        # We empty selection so that it loops and asks the question again
        selection = None

# Here we have an int
# If the selection is 1, 2 or 3, we display the menu. I use a list, 
# but range(1, 3) would have worked too
if selection in [1, 2, 3]:
    # Note I use an f-string here. You might not have learned about
    # them yet. Requires at least Python 3.6
    # This helps avoid repetition
    print(f"::menu {selection}::")
elif selection==4:
    # always call it like a function
    exit()
else:
    # Any other selection (remember, we know we have an int) should get this message
    print(f"There is no menu {selection}")
  • Related