0%

Values and Variables · practice

Build Messages with f-Strings

Programs often need to place values inside a sentence. Python’s make that direct and readable.

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."
  • f turns the into an f-string.

  • Text outside the braces appears literally.

  • {name} is replaced by the current of name.

  • {score} is replaced by the current value of score.

The result is one new string containing both text and values.

Run this example, then change temperature:

Try it

An f-string can insert strings, integers, and floats. You do not need extra quotation marks around names inside the braces.

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 inside braces. Beginning with variable names keeps the structure easy to inspect.

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 , check the spelling inside the braces. If it reports a , check the quotation marks and make sure every opening brace has a closing brace.

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 using activity, people, or ticket_total, respectively.

Produce exactly:

Plan: museum visit
People: 3
Ticket total: $36