Why does Python eval (input ("Enter input:")) change the input data type?

In Python 3, I write a simple command to receive integer input from a user this way:

x = int(input("Enter a number: ")) 

If I skip the int() and just use x = input("Enter a number: ") , my input data type is a string, not an integer. I understand it.

However, if I use the following command:

 x = eval(input("Enter a number: ")) 

input data type is 'int'.

Why is this happening?

+5
source share
2 answers

Why is this happening?

x = eval(input("Enter a number: ")) is not the same as x = eval('input("Enter a number: ")')

The first first calls input(...) , gets a string, for example. '5' then evaluates it, so you get int as follows:

 >>> eval('5') # the str '5' is eg the value it gets after calling input(...) 5 # You get an int 

While the latter (more consistent with the expected) evaluates the expression 'input("Enter a number: ")'

 >>> x = eval('input("Enter a number: ")') Enter a number: 5 >>> x '5' # Here you get a str 
+5
source

Since a number is a valid expression in Python and it evaluates to itself (and its type is int). For example, if you enter a garbage string with a nonexistent name (say "abcdefgh"), a NameError exception will be thrown (an exception occurs during evaluation).

0
source

All Articles