5: Input

In the last lesson we discussed user input, but did not really explain how user input is obtained. In Python, the user types one line of input at a time. You should use the input() function to actually obtain the next line of input from the user. The input() function takes no arguments and always gives back a str.

On this website, all input must be specified before the program runs. If you run Python interactively at home then input() actually pauses the program and waits until the user types a line of text.
Also, when working interactively, you can take advantage of the fact that input() accepts an optional string input, which will be interpreted as a prompt for the user. E.g.,

number = input("Enter a number between 0 and 100. ")

Here is an example of using input() to get input. The grader will automatically specify the input for the program.

Example
Echoing a line of text

The next example demonstrates:

  • By calling input() multiple times, you can access multiple lines of input. The first call to input() gets the first line, the second gets the second line, et cetera.
  • The string given by input() can be converted to an int or a float (like lesson 4)
  • In the second test case, the third line of input is not read, because input() is only called twice.

Example
 
You may enter input for the program in the box below.

From now on, most exercises allow the option of entering your own test input. Try the following experiment: press the Enter input button above. Leave the input text box empty. Then, press Run test. You should get an error like

EOFError: EOF when reading a line
The acronym EOF stands for End Of File. This message literally means that the program called input() but failed to have any available input to read.

  • Usually in our lessons, input is provided automatically by the grader, so this error could mean that your program called input() too many times, running out and going past the end of the grader's input.
  • However, in the example error you just caused, the input was user-provided, and you chose to provide no input, so the first call to input() was already too much.

For the next exercise, you are asked to debug a program which is not working, and make it work. Note that the bug is not a typo, but rather a logical bug: the program was not correctly designed to do its job, so you must redesign it a bit.

Coding Exercise: Echo
Write a program that reads one line of input, and prints out that same line two times. For example, if the input is Echo the output should be

Echo
Echo
Fix the broken sample solution given below. (Or, delete the whole sample solution and start from scratch.)  Hint
You may enter input for the program in the box below.

You can continue to the next lesson, which is about if statements.