Input in Python
User interaction is an important of computer programs as that input allows the program to react and respond to the uniqueness of the person using it.
Turn In: Input.py
Input is used in Python to get information from the person using the program. The most common way input is used is to assign it to a variable which stores the information provided by the user. Let's ask for the person's name then display it.
name = input("What is your name? ")
print("Hello ", name, "! Thank you for using this program.")
Notice that we put a prompt inside quotes inside the parenthesis of input. When the user types in their name it is stored in the variable name then print displays a welcome message that incorporates their name.
When run, it would look something like this ...
What is your name? Bob
Hello Bob! Thank you for using this program.
If you have not already run the program once or twice, do so now.
Next, let's ask for a number of dimes and display how much money that is.
dimes = input("How many dimes do you have? ")
total = dimes * 10
print(dimes, "is", total, "cents")
Run the code above and put in the number 5. 5 dimes should be 50 cents but instead we see ...
5 is 5555555555 cents
Python took our 5 as a string then duplicated the 5 ten times. So lets alter the line and tell it that dimes is an integer. The altered line will look like this ...
total = int(dimes) * 10
When run this time, we see that 5 is 50 cents.
Here is a variation where the input prompt includes a variable ...
firstname = "Bob"
lastname = input("Hello " + firstname + " what is your last name? ")
Run the code and observe how it works.
Copyright © 2022 Eric Schumm. Permission granted to freely use this in your classroom.