KaraageAndKamehameha
KaraageAndKamehameha

Reputation: 35

Input function not working in Python Code

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.

Upvotes: 1

Views: 3704

Answers (3)

Asta
Asta

Reputation: 1

The int() func is try to convert your string to Integer so it should be just numbers. It seems you are giving number and characters as an input so it raise the Value Error. if you want you can check if it is just numbers or not

x = input()
if x.isdigit():
   x = int(x)

Upvotes: 0

Delta Dev
Delta Dev

Reputation: 1

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.

Upvotes: 0

Marten Schl&#252;ter
Marten Schl&#252;ter

Reputation: 96

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}")

Upvotes: 1

Related Questions