skip to Main Content

I’m following a beginner’s Python course and the code the instructor has used works in PyCharm but not Visual Studio Code. I am learning how to use the try-catch within a while loop.

I have checked the Python version in Visual Studio Code and it is the same as in PyCharm (3.9).

I am not sure what is causing the error in Visual Studio Code. Can anyone help me troubleshoot this issue?

The code is:

while True:
    try:
        x = int(input("What is x? "))
    except ValueError:
        print("x is not an integer")
    else:
        break

print(f"x is {x}")

The code works as expected in PyCharm, but when I run it in Visual Studio Code, I get the following output:

What is x? print(f"x is {x}")
x is not an integer
What is x? 50

not as it should be which is:

What is x? cat
x is not an integer
What is x? 45
x is 45

2

Answers


  1. As i see vscode doesn’t execute the code outside of your loop, right? run the code in command line:

    python your_file.py

    if the output is same as PyCharm there might be something wrong with the configuration of your vscode, or maybe some extension causing errors

    Login or Signup to reply.
  2. Your code work perfectly.

    You’re receiving ValueError because the string input is being converted to int. what’ll happen if the user enter a letter or a character?

    A ValueError is a type of exception that is raised when a function or operation receives an argument with the correct data type but an inappropriate value. It occurs when the input value is not within the expected range or doesn’t fit the constraints defined by the function or operation.

    If you try to convert a string to an integer using the int() function, and the string does not represent a valid integer, a ValueError will be raised.

    for example:

    # Trying to convert a non-integer string (letters, characters) to an integer x = int(input("What is x? ")) # user input: & or A etc...

    This will result in a ValueError

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search