简体   繁体   中英

except ValueError not tripping Python 3.4

Alright so I'm trying to basically prevent someone from typing a string value into the field:

#User selection
print("Which program would you like to run?")
print("(Type '9' if you wish to exit the menu)")
selection = int(input())
print()

#Security statement followed by case statement
while selection <= 0 or selection >= 10:
    try:
        print("That is an invalid selection, please input a proper selection.")
        print("Which program would you like to run?")
        selection = int(input())
        print()
    except ValueError:
        print("Cmon man")

Plain and simple, it's not running. I've tried reorganizing everything and I haven't found a proper solution. Been looking around for almost an hour now. No help to the issue. Any kind souls?

Ignore the case statement portion btw, that's not even written yet.

PS Just keep getting usual "String isn't a number durr" response

("ValueError: invalid literal for int() with base 10: 'why'")

PPS Issue is already pointed out. I'm apparently stupidly oblivious lol... Thanks for the help.

Your try...except doesn't cover the initial user input and so the ValueError isn't actually caught. If you enter an int outside the bounds defined (0 >= x >= 10) as the first input then you can see the try...except blocks working.

You'll need to refactor your code so that the first input request is inside your try block and the loop or wrap the existing input request in another try...except .

Also, as a side note, input() can take a string argument that will be displayed as a prompt to the user.

selection = int(input("Which program would you like to run? "))

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