Soly
Soly

Reputation: 155

Why do I need to enclose input in quote marks?

I am working on Python2.7.6 and came across the following problem:

x=eval(input("Enter a number between 0 and 1: "))

Here, the input is supposed to create a string, but it's not running unless I wrap input in single quote marks too, check out the following:

x=eval('input("Enter a number between 0 and 1: ")')

Can someone please clarify why the first code wasn't running and the second one worked? It's really frustrating...I'd appreciate your help!

Upvotes: 0

Views: 100

Answers (1)

Blender
Blender

Reputation: 298146

In Python 2, input is just the composition of eval and raw_input. In effect, your first line is:

x=eval(eval(raw_input("Enter a number between 0 and 1: ")))

Typing in 123 will result in the first call to eval passing the integer 123 into the second eval function, which throws a nice error:

TypeError: eval() arg 1 must be a string or code object

Typing in '123' will make the string pass through unmodified, since eval("'123'") == '123'. Since you don't want to evaluate anything, just use raw_input:

x = raw_input("Enter a number between 0 and 1: ")

Upvotes: 1

Related Questions