Chapter 5: Formatted printing

Generic badge Open this in Colab

As we are already familiar with variables, there is a useful modification of the print command, to e.g. print out variables together with some annotion in a more convenient, “natural” way:

print(f"some description: {variable} more description")
  • simply take your text or annotation, but put a “f” in front of the quotation marks, and
  • where you want to use the value of a certain variable in this text, just plug-in that variable surrounded by {}
  • you can even do some calculations inside the brackets
# default print:
a = 8
b = 12
print("a:", a, "b:", b) # a lot of commas

a: 8 b: 12

# formatted print command:
print(f"Groupd A has {a} members, Groupd B has {b}.")

Groupd A has 8 members, Groupd B has 12.

# formatted print command with calculation:
print(f"In total we have {a+b} participants")

In total we have 20 participants

updated: