Why input() gives an error when I just press enter?

后端 未结 4 1903
囚心锁ツ
囚心锁ツ 2020-11-29 12:31

I have the following python code:

print \'This is a simple game.\'
input(\'Press enter to continue . . .\')
print \'Choose an option:\'

...
<
4条回答
  •  孤街浪徒
    2020-11-29 13:07

    For Python 2, you want raw_input, not input. The former will read a line. The latter will read a line and try to execute it, not advisable if you don't want your code being corrupted by the person entering data.

    For example, they could do something like call arbitrary functions, as per the following example:

    def sety99():
        global y
        y = 99
    
    y = 0
    input ("Enter something: ")
    print y
    

    If you run that code under Python 2 and enter sety99(), the output will 99, despite the fact that at no point does your code (in its normal execution flow) purposefully set y to anything other than zero (it does in the function but that function is never explicitly called by your code). The reason for this is that the input(prompt) call is equivalent to eval(raw_input(prompt)).

    See here for the gory details.

    Keep in mind that Python 3 fixes this. The input function there behaves as you would expect.

提交回复
热议问题