Night 16: Name tags
你已使用 Python 或伪代码完成过这个夜间练习,两种语言均计入完成记录。你可以再次练习。
此页面需较新浏览器(支持 SharedArrayBuffer)。请升级 Chrome、Edge、Firefox 或 Safari 至最新版本。
English
Tonight: name tags
- Your pet wants a name tag. Tonight you put values inside text.
- You will learn one thing: f-strings.
Words for tonight
| Word | Meaning |
|---|---|
| f-string | a text with an f in front; values can go inside it |
| braces | the brackets { } |
| space | the empty character between words |
English
Values inside text
- Put
fbefore the first quote. Then write variable names inside{ }.
name = "Kit"
age = 2
print(f"{name} is {age} years old")
- Python puts each value where its braces are.

English
Commas or an f-string?
| Code | Output |
|---|---|
print(snack, ":", price) |
apple : 3 |
print(f"{snack}: {price}") |
apple: 3 |
- Commas always add a space. In an f-string you choose the spaces.
English
Maths inside the braces
- Python works out what is inside
{ }first.
age = 2
print(f"Next year: {age + 1}")
print(f"In dog years: {age * 7}")
English
Do not forget the f
- Without
f, the braces are just normal text:
name = "Kit"
print("{name} is sleepy")
print(f"{name} is sleepy")
- Now make some name tags!
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
Read a name, then an age with int(input()). Use an f-string to print Kit is 2 years old.
点击“运行”查看此处输出。
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
Read a snack and a price. Print a price tag like apple: 3 coins. There is no space before the :.
点击“运行”查看此处输出。
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
Read a name and an age. Print Next year Kit is 3. Work out age + 1 inside the { }.
点击“运行”查看此处输出。
难度 3/5 · 今日首次完成可获 200 金币及少量额外奖励
Read a name, a kind and a number of nights. Print a 3-line card: Name: Kit, then Kind: fox, then Nights: 12/30.
点击“运行”查看此处输出。