Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Prompting for user input in Python 3

  • input
  • prompt
  • STDIN

In Python 3 the raw_input() function was replaced by the input() function.

def main():
    print("We have a question!")
    name = input('Your name: ')
    print('Hello ' + name + ', how are you?')

main()

What happens if you run this using Python 2 ?

/usr/bin/python2 prompt3.py
  • What happens if we type in "Foo Bar"
We have a question!
Your name: Foo Bar
Your name: Traceback (most recent call last):
  File "prompt3.py", line 5, in <module>
    main()
  File "prompt3.py", line 2, in main
    name = input('Your name: ')
  File "<string>", line 1
    Foo Bar
          ^
SyntaxError: unexpected EOF while parsing
  • What happens if we type in just "Foo" - no spaces:
We have a question!
Your name: Foo
Your name: Traceback (most recent call last):
  File "prompt3.py", line 5, in <module>
    main()
  File "prompt3.py", line 2, in main
    name = input('Your name: ')
  File "<string>", line 1, in <module>
NameError: name 'Foo' is not defined
  • The next example shows a way to exploit the input function in Python 2 to delete the currently running script. You know, just for fun.
We have a question!
Your name: __import__("os").unlink(__file__) or "Hudini"
Hello Hudini, how are you?