f-strings, explained simply
Suppose you want to greet every player by name. Writing a separate message for each person would take forever. An f-string lets one message fill itself in.
Put the letter f right before the opening quotation mark, then write a variable name inside curly brackets { }. When the line runs, Python swaps the brackets for the value stored in the variable.
You can put more than one variable in the same message, and even small calculations like {score * 2}.
Example: A message that fills itself in
player = "Asha"
score = 12
print(f"Well done, {player}! You scored {score} points.")Output
Well done, Asha! You scored 12 points.Try this
- Change player to your own name and run it again. The message updates without touching the print line.
- Remove the f and see what gets printed instead.
- Add a variable for a pet name and put it in the same sentence.
