What is the point of using code, like on line 8 and 9, when we can use print
like on line 10?
my_name = 'Zed A. Shaw'
my_age = 35
my_height = 74
my_weight = 180
my_eyes = 'Blue'
my_teeth = 'White'
my_hair = 'Brown'
print(f"Let's talk about {my_name}.") # Line 8
print(f"He's {my_height} inches tall.") # Line 9
print("He's", my_teeth, "pounds heavy.") # Line 10
What you're seeing on lines 8-9 are called formatted string literals or f-strings for short. They were added to Python in version 3.6, and detailed in PEP498. They basically allow you to embed expressions directly in strings.
So, what is the point of using them over the normal call to
print
? In the example above, not much. The real benefit is shown when you need to format strings using multiple values. Rather than doing doing a bunch of string concatenation, you can directly use the name of a variable or include an expression in the string:Although is may be hard to tell from the above examples, f-strings are very powerful. Being able to embed entire expressions inside of a string literal is a very useful feature, and can also make for more clear and concise code. This will be become very clear when you begin to write more code and the use cases for your code becomes non-trivial.