User Input

Obtaining runtime user input in Python is fairly simple, and is done via built-in functions.

input() returns a string, with the trailing newline removed from the input.

print("Enter some data: ", end='')
data = input()

data now contains a string, provided by the user.

If you would like the user to enter a specific kind of data, something like this can be used.

try:
   data_int = int(input("Enter an integer: "))
except ValueError:
   print("Error: input was not an integer")
   exit(1)

Or something like this, if you would like to ask continuously for input until the input is valid.

complete = False
while not complete:
   try:
      data_int2 = int(input("Enter another integer: "))
      complete = True
   except ValueError:
      print("Please enter an integer.")

If the ValueError exception is thrown, the loop will be run again, and the input will also be asked for once more.

A standard 'yes or no' question might look like this:

yes_no = input("Would you like to print out the results of the the previous inputs? [Y/n] ")

while yes_no not in ['y', 'Y', 'n', 'N']:
   yes_no = input("Sorry, response '%s' not understood. [Y/n] " % yes_no)

And of course, once the input is properly received, it can be handled like any other data.

if yes_no in ['Y', 'y']:
   all_data = (data, data2, data_int, data_int2)
   print(*all_data)