Why does this happen?
x = eval(input("Enter a number: ")) is not the same thing as x = eval('input("Enter a number: ")')
The former first calls input(...), gets a string, e.g. '5' then evaluates it, that's why you get an int, in this manner:
>>> eval('5') # the str '5' is e.g. the value it gets after calling input(...)
5 # You get an int
While the latter (more aligned with what you were expecting), evaluates the expression 'input("Enter a number: ")'
>>> x = eval('input("Enter a number: ")')
Enter a number: 5
>>> x
'5' # Here you get a str
Answer from bakkal on Stack OverflowIs eval a keyword in python?
What is eval ()?
What are the eval's parameters?
Videos
Why does this happen?
x = eval(input("Enter a number: ")) is not the same thing as x = eval('input("Enter a number: ")')
The former first calls input(...), gets a string, e.g. '5' then evaluates it, that's why you get an int, in this manner:
>>> eval('5') # the str '5' is e.g. the value it gets after calling input(...)
5 # You get an int
While the latter (more aligned with what you were expecting), evaluates the expression 'input("Enter a number: ")'
>>> x = eval('input("Enter a number: ")')
Enter a number: 5
>>> x
'5' # Here you get a str
Because a number is a valid expression in Python, and it evaluates to itself (and its type is int). For example, if you input a rubbish string with a non-existing name (say, 'abcdefgh'), a NameError exception will be raised (the exception is raised while evaluating).
I want to use eval() to convert a string gotten from input() to a list. I’ve tried most of what i know but it doesn’t work. I’m not familiar with the eval() function.
The eval function lets a Python program run Python code within itself.
eval example (interactive shell):
>>> x = 1
>>> eval('x + 1')
2
>>> eval('x')
1
eval() interprets a string as code. The reason why so many people have warned you about using this is because a user can use this as an option to run code on the computer. If you have eval(input()) and os imported, a person could type into input() os.system('rm -R *') which would delete all your files in your home directory. (Assuming you have a unix system). Using eval() is a security hole. If you need to convert strings to other formats, try to use things that do that, like int().