Back to: Python Programming
How to accept User Input in Python
Accepting user input allows your program to interact with the user. The ability to request information is an important feature of all programming languages. To accept user input we can use the ‘input’ function with a ‘string’ prompt to receive the input and assign it to a variable. We can then use this information within our program.
name = input("What is your name? ")
print(f"Hello, {name}!")
Execution of the program will pause until the user responds to the prompt for data.
Output:
What is your name? Bob
Hello, Bob!
When we accept user input, it is always of the ‘string’ data type. When entering data that we need as an ‘integer’ or ’float’ data type, we need to typecast it.
name = input("What is your name? ")
driving_hours = input("How many driving hours have you accumulated on your L's? ")
driving_hours = int(driving_hours)
remaining_hours = 120 - driving_hours
print(f"Gidday {name}!")
print(f"You have {remaining_hours} hours to go before testing for your P plates.")
Output:
What is your name? Sandra
How many driving hours have you accumulated on your L's? 108
Gidday Sandra!
You have 12 hours to go before testing for your P plates.
What does the following code do differently?
name = input("What is your name? ")
driving_hours = int(input(f"How many driving hours have you accumulated {name}? "))
remaining_hours = 120 - driving_hours
print(f"Gidday {name}!")
print(f"You have {remaining_hours} hours to go before testing for your P plates.")
Simple Calculations and Rounding
When using user input for any type of mathematics, we need to typecast number to ‘int’ or ‘float’ and results may have many decimal places, so often we prefer to round our answers to a few decimal places.
item = input("What item are you bidding on?: ")
price = float(input("What is your maximum bid?: $"))
quantity = int(input("How many items do you want to bid?: "))
total = price * quantity
print(f"The total price for {quantity} {item}'s at ${price}")
print(f"will be ${round(total,2)}") # <-- the 2 is the number of DP's
Output:
What item are you bidding on?: iPhone
What is your maximum bid?: $482.63
How many items do you want to bid?: 2
The total price for 2 iPhone's at $482.63
will be $965.26
Exercise:
By asking a user for some information, write code to generate an email ‘signature’ for them. The ‘sig’ should look like the sig below.
Note: The time servicing the community is to be calculated – NSC opened in 1958.
Best Regards,
Shane Dickinson
IT Teacher
Norwood Secondary College
serving the community for 66 years
Exercise:
Write a program to calculate the Area and Perimeter of a Rectangle after asking the user for the Length and the Width.
Remember: User input is treated as a ‘string’ until you typecast it.