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. Your program uses the input() function to actually obtain the next line of input from the user. The input() function always gives back a str; as we saw in lesson 4, this can be converted to an int or a float.

On this website, all input must be specified before the program runs. All the lessons are built to run this way. However, if you run Python at home then you can use “interactive input” while the program is still running.

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

Example
Using input()

Notice that in the last test case, the second line of input was not even read, because input() was only called once. By calling input() multiple times, you can access multiple lines of input.

From now on, most exercises allow the option of entering your own test input; here is a very simple example.

Example
Echoing a line of text
You may enter input for the program in the box above.

Try the following experiment: press the Enter input button above. Leave the input text box empty, or delete anything you typed in there. 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 means that when the program tried to get more input, all of the lines of input had already been read (used up), causing the error.

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 above.

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