I wrote a function in Python which prompts the user to give two numbers and adds them. It also prompts the user to enter a city and prints it. For some reason, when I run it in
In Python 2.x, input asks for a Python expression (like num1 + 2
) which is then evaluated. You want raw_input which allows one to ask for arbitrary strings.
You want raw_input
, not input
.
input(...)
input([prompt]) -> value
Equivalent to eval(raw_input(prompt)).
As opposed to...
raw_input(...)
raw_input([prompt]) -> string
Read a string from standard input. The trailing newline is stripped.
If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.
On Unix, GNU readline is used if enabled. The prompt string, if given,
is printed without a trailing newline before reading.
you want to use raw_input
. input
is like eval
You want to use raw_input()
instead. input()
expects Python, which then gets eval
ed.
If you're on Python 2, you need to use raw_input
:
def func_add(num1, num2):
a = raw_input("your city")
print a
return num1 + num2
input
causes whatever you type to be evaluated as a Python expression, so you end up with
a = whatever_you_typed
So if there isn't a variable named whatever_you_typed
you'll get a NameError
.
With raw_input
it just saves whatever you type in a string, so you end up with
a = 'whatever_you_typed'
which points a
at that string, which is what you want.
input()
executes (actually, evaluates) the expression like it was a code snippet, looking for an object with the name you typed, you should use
raw_input()
This is a security hazard, and since Python 3.x, input() behaves like raw_input(), which has been removed.