What's the difference between `raw_input()` and `input()` in Python 3?

后端 未结 6 1678
执笔经年
执笔经年 2020-11-21 04:19

What is the difference between raw_input() and input() in Python 3?

6条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-21 05:00

    In Python 3, raw_input() doesn't exist which was already mentioned by Sven.

    In Python 2, the input() function evaluates your input.

    Example:

    name = input("what is your name ?")
    what is your name ?harsha
    
    Traceback (most recent call last):
      File "", line 1, in 
        name = input("what is your name ?")
      File "", line 1, in 
    NameError: name 'harsha' is not defined
    

    In the example above, Python 2.x is trying to evaluate harsha as a variable rather than a string. To avoid that, we can use double quotes around our input like "harsha":

    >>> name = input("what is your name?")
    what is your name?"harsha"
    >>> print(name)
    harsha
    

    raw_input()

    The raw_input()` function doesn't evaluate, it will just read whatever you enter.

    Example:

    name = raw_input("what is your name ?")
    what is your name ?harsha
    >>> name
    'harsha'
    

    Example:

     name = eval(raw_input("what is your name?"))
    what is your name?harsha
    
    Traceback (most recent call last):
      File "", line 1, in 
        name = eval(raw_input("what is your name?"))
      File "", line 1, in 
    NameError: name 'harsha' is not defined
    

    In example above, I was just trying to evaluate the user input with the eval function.

提交回复
热议问题