Learn how to accept user input in your Python programs.
An important aspect of computer science is creating interactive programs for users. A large part of user interaction is allowing users to input information into a program.
In Python, we use the input()
function to ask the user for input. As a parameter, we input the text we want to display to the user. Once the user presses “enter,” the input value is returned. We typically store user input in a variable so that we can use the information in our program.
Take a look at the following program to get a feel for how user input works. Run the program and explore with these guiding questions:
input()
returns?You should have noted that input()
returns the user input as a string, even if the user inputs a number! This can cause complications if you’re wanting to do any calculating with the number. Luckily, you can easily convert strings to integers in Python by using the int()
function. This is also known as casting, which you can learn more about at here.
Take a look at the slides to see how you can use both the int()
and input()
functions to obtain numerical information from the user.
See the int(input())
command in action in the program below, and explore how it works with these guiding questions:
int()
function in line 1? Why does this happen?Now that you know the basics of user input, try it out by completing the following exercises. In each program, you should use variables to store the information gathered from the user.