Values and Variables · practice
Build Messages with f-Strings
Programs often need to place values inside a sentence. Python’s
name = "Sam"
score = 8
print(f"{name} scored {score} points.")
The output is:
Sam scored 8 points.
The letter f before the opening quotation mark tells Python to look for values inside curly braces.
Read an f-string in parts
In this f-string:
f"{name} scored {score} points."
fturns theinto an f-string. Text outside the braces appears literally.
{name}is replaced by the currentof name.{score}is replaced by the current value ofscore.
The result is one new string containing both text and values.
Run this example, then change temperature:
An f-string can insert strings, integers, and floats. You do not need extra quotation marks around
The braces contain Python
For now, put a variable name inside each pair of braces:
item = "notebook"
quantity = 3
print(f"Item: {item}")
print(f"Quantity: {quantity}")
Later, you will also use
Common slips
If you forget the f, Python prints the braces as ordinary text:
name = "Sam"
print("Hello, {name}")
The output is Hello, {name}.
If Python reports a
What will this program print?
fruit = "pears"
amount = 4
print(f"We have {amount} {fruit}.")Print a short plan
The starter program already contains three variables. Replace its final print instruction with three print instructions, each displaying a line built with an f-string, so the output is exactly:
Plan: museum visit
People: 3
Ticket total: $36
Use the variables inside braces. The dollar sign is ordinary text and belongs outside the braces.
Keep the three starting values unchanged. Press Run after each line if that makes the structure easier to check.
Task
Replace the final print instruction with three print instructions. Build each line with an activity, people, or ticket_total, respectively.
Produce exactly:
Plan: museum visit
People: 3
Ticket total: $36