Home > Enterprise >  Input function not working in Python Code
Input function not working in Python Code

Time:03-12

I was writing a python code in VS Code and somehow it's not detecting the input() function like it should. Suppose, the code is as simple as

def main():    
    x= int ( input() )
    print(x)

if __name__ == "__main__":
    main()

even then, for some reason it is throwing error and I cannot figure out why. The error being- enter image description here

P.S. 1)I am using Python 3.10 2) I tried removing the int() and it still doesn't work.

CodePudding user response:

The traceback shows you where to look. It's actually the int function throwing a ValueError. It looks as if you're feeding it a filepath whereas it it's expecting a number.

You could add a check to repeat the input if incorrect like so:

user_input = None
while not user_input:
    raw_input = input("Put in a number: ")    
    try:
        user_input = int(raw_input)
    except ValueError:
        continue

print(f"Number is: {user_input}")

CodePudding user response:

it's working!!!

see my example that says why you don't understand this:

>>> x1 = input('enter a number: ')
enter a number: 10
>>> x1
'10'
>>> x2 = int(x1)
>>> x2
10
>>> x1 = input()  # no text
100
>>> # it takes
>>> x1
'100'
>>> # but how you try?
>>> x1 = input()
NOT-NUMBER OR EMPTY-TEXT
>>> x2 = int(x1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'IS-NOT-NUMBER OR EMPTY TEXT'
>>>

I thing this is enough.

  • Related