2

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 a shell, I get "name is not defined" after I enter the city.

def func_add(num1, num2):
   a = input("your city")
   print a
   return num1 + num2 
agf
  • 171,228
  • 44
  • 289
  • 238
chris005
  • 21
  • 1
  • 1
  • 2
  • Not really a duplicate of that (though it might be a duplicate of others), since it doesn't explain the difference between `raw_input` and `input` or that `raw_input` is specific to Python 2. – agf Sep 16 '11 at 20:59

6 Answers6

9

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.

agf
  • 171,228
  • 44
  • 289
  • 238
1
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.

Marco Mariani
  • 13,556
  • 6
  • 39
  • 55
0

you want to use raw_input. input is like eval

Foo Bah
  • 25,660
  • 5
  • 55
  • 79
0

You want to use raw_input() instead. input() expects Python, which then gets evaled.

CanSpice
  • 34,814
  • 10
  • 72
  • 86
0

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.
nmichaels
  • 49,466
  • 12
  • 107
  • 135
0

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.

phihag
  • 278,196
  • 72
  • 453
  • 469