F-strings
Joining text with + works, but with more values, it becomes hard to read: every number needs str(), and it's easy to forget a space or a quote:
first_name = "Anna"
age = 25
print("My name is " + first_name + " and I am " + str(age) + " years old.")There is an easier way: an f-string. It's text with the letter f right before the opening quote. You insert a value into it by writing it in curly braces {}:
first_name = "Anna"
age = 25
print(f"My name is {first_name} and I am {age} years old.")Both examples print:
My name is Anna and I am 25 years old.Python replaces every {...} with the value inside it, and numbers work without str(). The spaces are part of the text, so you can see right away where they are. The f stands for “formatted”.
You can even put a calculation inside the braces:
price = 120
print(f"Two tickets cost {price * 2} dollars.")This prints:
Two tickets cost 240 dollars.Don't forget the f. Without it, the braces are just text, and they are printed as they are:
day = "Monday"
print("Today is {day}.")This prints:
Today is {day}.An f-string is a string like any other, so you can also store it in a variable. From now on, we'll use f-strings whenever we put values into text.
Instructions
Create a variable forecast with an f-string that inserts the values of day and temperature into the text On Monday it will be 25 degrees.
In the text, replace Monday with {day} and 25 with {temperature}.
Print forecast. The output should be On Monday it will be 25 degrees.
On the next line, print the forecast for the following day, when it will be 2 degrees warmer. Use an f-string with a calculation inside the braces, so that the program prints A day later it will be 27 degrees.
Start programming for free
9/11