简体   繁体   中英

Try/except statement not catching ValueError when converting string to int in python 3

I am trying to convert get input from the user as an integer only, and provide error checking to make sure the user's input is valid. When checking to see if the user has entered a string, the program is supposed to display an error if what the user enters is not an integer. However, no matter how I structure this try/except, it is not displaying the error message, and instead bouncing me back to the Visual Studio editor and throwing the exception "invalid literal for int() with base 10". I have searched and searched all over this site and others, and everybody else with this issue is able to get it working using this code, but for some reason for me it just is not working. Can someone please help me figure out what is going wrong, or if there is another way to check for integer input, please point me in that direction. Any assistance is appreciated, and I apologize if there is a similar question on this site already, but I was unable to find one pertaining to my specific case. I am using the Python 3.7 interpreter (although 3.8 is what I have installed, VS does not yet support it). Here is my code:

    try:
        a = int(input("Input: "))
    except ValueError:
        print(a)

The code that you show is wrong.

If an exception occurs, then a will not have been assigned. The code that was working for others was probably very similar but different.

Here an example with try except, that prompts the user until there is some valid input. It also prints the path to the python executable and its version in order to be sure, that this is not a version issue. an IDE should not be able to ignore a try except statement.

I never heard of something like this and assume, that there is some other difference than pycharm vs Visual studio code.

import sys
print(sys.executable, sys.version_info)  # for debugging only
while True:
    inp = input("Input: ")
    try:
        a = int(inp)
        break
    except ValueError:
        print("invalid input", inp, ". You should enter a number. Please retry")

print("A is", a)

I don't know whether you want to force the user to enter correct data or whether you just want to detect an error. Just adapt it to your exact needs

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