How do I get user input from the keyboard in Python 2?

前端 未结 6 1224
悲哀的现实
悲哀的现实 2021-01-23 03:49

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

6条回答
  •  离开以前
    2021-01-23 04:23

    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.

提交回复
热议问题