Intro to Computer Science / Unit 4: Programming Basics in Python
4.4 Input and Formatting Output
Notes
The input() function reads what the user types. It always returns a string, so convert it to a number when you need math.
age = int(input("Age? "))
print("Next year you will be", age + 1)
- If the user types
14, the program printsNext year you will be 15. - Without
int(),age + 1would cause an error, because you cannot add a string and an integer. - An f-string puts values inside text:
f"Hello, {name}!". - Example: with
name = "Sam",print(f"Hi {name}")showsHi Sam.
Practice
What type of value does
input() return?input() always gives a string, even if the user types digits.
A user types 8 when running
n = input("n? "); print(n * 2). What is printed?n is the string "8", and "8" * 2 repeats it to give "88".
With
item = "pen" and cost = 3, what does print(f"{item} costs {cost + 1}") show?The f-string replaces {item} with pen and evaluates cost + 1 as 4.
Ready for more? Take the Unit 4 test.