2.8. InputΒΆ
Programs are more useful if the user can change the behavior of the program by
giving the program input. In Python there is a built-in function to accomplish
this task. As you might expect, it is called input
.
name: str
print("Please enter your name")
name = input()
The user of the program can enter the name and press return. When this happens the text that has been entered is returned from the input function, and in this case assigned to the variable 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"
. It would be your job, as the
programmer, to convert that string into an int or a float, using the
int
or float
converter functions we saw earlier.
To modify our previous program, we will add an input statement to allow the user to enter the number of seconds. Then we will convert that string to an integer. From there the process is the same as before. To complete the example, we will print some appropriate output.
The variable str_seconds
will refer to the string that is entered
by the user. As we said above, even though this string may be
7684
, it is still a string and not a number. To convert it to an
integer, we use the int
function. The result is referred to by
total_secs
. Now, each time you run the program, you can enter a
new value for the number of seconds to be converted.
Check your understanding
seconds = input() hours = int(seconds) // 3600 total_secs = int(seconds) secs_still_remaining = total_secs % 3600
seconds = input() hours = int(seconds) // 3600 total_secs = int(seconds) secs_still_remaining = total_secs % 3600