In my book , Python Crash Course : This code is given but it gives an error.
def make_pizza(*toppings):
"""Summarize the pizza we are about to make."""
print("\nMaking a pizza with the following toppings:")
for topping in toppings:
print("- " + topping)
make_pizza(make_pizza("peperoni"))
make_pizza(make_pizza("mushroom",'green peppers','extra cheese'))
The traceback is as follows:
print("- " + topping)
TypeError: cannot concatenate 'str' and 'NoneType' objects
Q. What is the NoneType object here ? Is it topping? If yes, why?
Even when i use str()
around topping
, It gives me a funny output:
def make_pizza(*toppings):
"""Summarize the pizza we are about to make."""
print("\nMaking a pizza with the following toppings:")
for topping in toppings:
print("- " + str(topping))
make_pizza(make_pizza("peperoni"))
make_pizza(make_pizza("mushroom",'green peppers','extra cheese'))
Output:
Making a pizza with the following toppings:
- peperoni
Making a pizza with the following toppings:
- None
Making a pizza with the following toppings:
- mushroom
- green peppers
- extra cheese
Making a pizza with the following toppings:
- None
Q2. Why is displaying 2 outputs for each? - one with the list of toppings -and one with None ?
You shouldn't be passing the function to itself.
Replace these:
make_pizza(make_pizza("peperoni"))
make_pizza(make_pizza("mushroom",'green peppers','extra cheese'))
with
make_pizza("peperoni")
make_pizza("mushroom",'green peppers','extra cheese')
The reason that the error is happening is because you are passing the function make_pizza
, which has no return value (it returns nothing), to itself.
However , the inner function still executes completely. That is, the second make_pizza
in each of your examples is running properly, which is why you're getting two outputs.
For the second function though, you're effectively trying to run:
make_pizza(None)
Which of course leads to an error here:
print("- " + topping)
because topping
is None
.
The reason you sometimes saw - None
in your output is because str(None)
casts None
to "None"
(as in, a string containing the literal text None
).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.