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

前端 未结 6 1223
悲哀的现实
悲哀的现实 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 03:59

    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.

    0 讨论(0)
  • 2021-01-23 04:15

    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.
    
    0 讨论(0)
  • 2021-01-23 04:19

    you want to use raw_input. input is like eval

    0 讨论(0)
  • 2021-01-23 04:19

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

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-23 04:25
    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.

    0 讨论(0)
提交回复
热议问题