Stuck on #5

Stuck on #5. What is wrong that needs to be corrected?

The dollar sign is character data (and looks more like JS in this usage). Plus if you wish to concatenate a string with a number it needs to be cast as str().

When using print formatting we don’t need to cast. It looks like that is what you had in mind…

print (f"We sell {num_pizzas} different kinds of pizzas.")

with your correction I get this message:

TypeError: must be str, not int

Please show the new code.

print('We sell + {num_pizzas} + different kinds of pizza!')
#             ^                ^

Missing quotes where indicated. Remember to include a space character inside the quotes. num_pizzas will need to be cast as str() so it may be concatenated.

thanks for the help!

1 Like

Of note is your use of { and } which is placeholder syntax for string formatting. If it has come up in your lessons, check out the three methods…

%           =>  modulo formatting (inherited from C)
format()    =>  added late in version 2
f-string    =>  introduced in version 3.5(ish)

https://pyformat.info/

The code you have above is closest to f-string

print (f"We sell {num_pizzas} different kinds of pizza!")

The variable is interpolated into the string.

thanks I’ll look over these

1 Like

The nice thing about string formatting is that it does not mutate the data. We can round without using floor() or round() and get decent precision. If we only want to represent the data, then we won’t find a better option.

>>> from math import pi as PI
>>> print (f"{PI} is usually rounded to {PI:.2f}")
3.141592653589793 is usually rounded to 3.14
>>> 

Above we’ve given an alias of PI to indicate to a reader that it is a constant in the global namespace. We are free to represent it any way we choose, hopefully never changing it.

What’s neater is that we can assign formatted strings as data.

>>> pi = f"{PI:.4f}"
>>> pi
3.1415
>>> 

Mind that it is still character data. Easier in computation if we cast it to float when we are actually using it. But then, why would we ever use it to compute when we have the global constant?


Addendum

Print formatting techniques, whichever we choose are applied to all forms of Python quotes.

''
""
''''''
""""""

The latter two support preformatted text so may contain line breaks. This is especially useful when setting prose with interpolated data in a game or a report setting. The text is stored off to the side and polled only when needed with the data punched in when it is streamed to the output device.