Python-Ref > User interaction > User input > Interactive user input
 
 

<-^^
Klíčová slova
Moduly
Knihovní funkce

Interactive user input

How to ask the user questions during program execution.
Sometimes it is useful to be able to ask the user questions during program execution. Even though it is often not the best idea to do so in automated scripts that might be even run automatically without the user knowing, it enables creation of interactive programs.
Expand/Shrink
Zdroj: (userinp4-1.py)
  1   # test if the user can do some basic math
  2   print "What is the result of the following equation?"
  3   print "4 * 5 - 3 - 2 * 6"
  4   result = 4 * 5 - 3 - 2 * 6
  5   answer = None
  6   while answer != result:
  7     # for simplicity we do not check if a number was really given,
  8     # therefore the program will crash with answer that is not a number
  9     answer = int( raw_input( "answer>> "))
 10     if answer == result:
 11       print "OK"
 12     else:
 13       print "No! Try again"
stdout:
What is the result of the following equation?
4 * 5 - 3 - 2 * 6
answer>> 1
No! Try again
answer>> 4
No! Try again
answer>> 5
OK
Doba běhu: 437.0 ms
The features of the input line that the raw_input function creates may be enhanced by importing the readline library. This will change the behavior of the command line and enable some editing features as well as command history.