简体   繁体   中英

integer input validation python

can't seem to get this loop to work, it keeps looping back to the Binary Number Input. I'd like it to loop back to the menu selection. Sorry for the noob question I'm new to python and programming.

import sys
loop = 0
menu_Select = 0
for menu_Select in range(1,100):
    #Display user options to the screen
    print('*** Menu ***')
    print('1. Convert to binary')

    userMenu = input('What would you like to do [1,2,3,4]? ')
    if userMenu != '1' and userMenu != '2' and userMenu != '3' and userMenu != '4':
        print("Please enter either 1, 2, 3, or 4.")

    elif userMenu == '4':
        print('Goodbye.')
        sys.exit(0)

    elif userMenu == '1':
        #Decimal to Binary convertion code
        print('\n')
        while loop < 1:
            while True:
                try:
                    user_Number = (int(input('Please enter number: ')))
                except ValueError:
                    print('wrong')
                else:
                    binary_num = []

                    while (user_Number > 0):
                        if user_Number % 2 != 0:
                            binary_num.append(1)
                        elif user_Number % 2 == 0:
                            binary_num.append(0)
                        user_Number = user_Number // 2
                    binary_num.reverse()
                    binary_display = ''.join(str(k) for k in binary_num)
                    print('Binary number: ',binary_display)
            loop += 1

Using input() will actually convert what the user types into an int if it can. So take a look at what happens:

>>> input("= ")
= 12
12

That returns 12, not '12'. For input to give me '12' I need to manually wrap it in quotes.

>>> input("= ")
= '12'
'12'

Instead, use raw_input() to get Python to read anything the user types as a string.

>>> raw_input("= ")
= 12
'12'

Also, as others have mentioned you're using the while loops wrong. If you want to keep asking the user for input until you get a valid number, it's better to wrap a smaller amount of code with the relevant condition.

ie. Have the loop only run while there isn't a valid number, and have it only contain the lines where the input is happening.

        user_Number = None
        while user_Number is None:
            try:
                user_Number = (int(raw_input('Please enter number: ')))
            except ValueError:
                print('wrong')
        binary_num = []

        while (user_Number > 0):
            if user_Number % 2 != 0:
                binary_num.append(1)
            elif user_Number % 2 == 0:
                binary_num.append(0)
                user_Number = user_Number // 2
        binary_num.reverse()
        binary_display = ''.join(str(k) for k in binary_num)
        print('Binary number: ',binary_display)

You can introduce a boolean variable done = False , before the while True loop, and change this loop to while not done . Then set done to True after the binary number was printed.

elif userMenu == '1':
    #Decimal to Binary convertion code
    print('\n')
    done = False
    while not done:
        try:
            user_Number = (int(input('Please enter number: ')))
        except ValueError:
            print('wrong')
        else:
            binary_num = []
            while (user_Number > 0):
                if user_Number % 2 != 0:
                    binary_num.append(1)
                elif user_Number % 2 == 0:
                    binary_num.append(0)
                user_Number = user_Number // 2
            binary_num.reverse()
            binary_display = ''.join(str(k) for k in binary_num)
            print('Binary number: ',binary_display)
            done = True

Change:

if userMenu != '1' and userMenu != '2' and userMenu != '3' and userMenu != '4':

To:

if userMenu != 1 and userMenu != 2 and userMenu != 3 and userMenu != 4:

And also update your if statements to see if they are int's rather than strings. This will work on python 2.7, not sure about python 3.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM