Skip to main content

Section 2.9 Input

The program in the previous section works fine, but is very limited in that it only works with one value for total_secs. What if we wanted to rewrite the program so that it was more general? One thing we could do is allow the user to enter any value they wish for the number of seconds. The program could then print the proper result for that starting value.
In order to do this, we need a way to get input from the user. Luckily, in Python there is a built-in function to accomplish this task. As you might expect, it is called input.
your_name = input("Please enter your name: ")
The input function allows the user to provide a prompt string. When the function is evaluated, the prompt is shown. The user of the program can enter the name and press (return or ENTER on your keyboard). When this happens, the text that has been entered is returned from the input function, and in this case assigned to the variable your_name. Make sure you run this example a number of times and try some different names in the input box that appears.
It is very important to note that the input function returns a string value. Even if you asked the user to enter their age, you would get back a string like "17" (even though the quote marks wouldn’t show up when you printed it). The problem here is that we can’t mix strings and numbers. If we try starting our program like this and enter a number like 7468:
Python will complain bitterly that we cannot mix strings and integers:
TypeError: unsupported operand type(s) for //: 'str' and 'int'
That leaves one piece of the puzzle that we need to solve in order to write our program, and we will look into that missing piece on the next page.