The basics of syntax

INPUT · Slides

Dropping values into a sentence

01 / 06

What is annoying about the ways we have

You want to show "Aoi's score is 95%". With what we have so far, commas are the only option.

print(name, "'s score is", 95, "%")

But a comma always drops a space in, so you end up with "Aoi 's score is 95 %". Not what you meant.

name = "Aoi"print(name, "'s score is", 95, "%")

Result

Aoi 's score is 95 %

02 / 06

Use an f-string

So: the f-string. Put an f in front of the quote and wrap anything you want dropped in with { }.

The best part is that you can see the finished sentence. Writing it while looking at the shape of the result means you stop losing spaces.

name = "Aoi"print(f"{name}'s score is 95%")

Result

Aoi's score is 95%

03 / 06

Forget the f and nothing lands

Here is the usual slip. Leave the f off and the { } show up as they are.

It is not an error, so it is easy to miss. If you see {name} on screen, look at what is in front of the quote.

name = "Aoi"print("{name}'s turn")

Result

{name}'s turn

04 / 06

Drop in as many as you like

You can put as many { } in one sentence as you want, and a variable holding a number goes in just the same.

No being told off about text and numbers not adding, the way + did. That is another reason people reach for f-strings.

name = "Aoi"age = 18print(f"{name} is {age} years old")

Result

Aoi is 18 years old

05 / 06

A sum can go inside too

Inside { } you can put more than a variable — a whole sum works, and the answer lands in its place.

Do not cram too much in, though. Work a long sum out into a variable first and your reader will thank you.

unit_price = 250count = 4print(f"that comes to ${unit_price * count}")

Result

that comes to $1000

06 / 06

The three ways side by side

Here are three attempts at the same output.

  • print(name + "'s turn") … no numbers allowed in
  • print(name, "'s turn") … a space appears whether you want one or not
  • print(f"{name}'s turn") … exactly what you meant

If you are unsure, use an f-string. In real Python today, this is what you will see most.

name = "Aoi"print(f"{name}'s turn")

Result

Aoi's turn