0

Can anyone explain the syntax of Pizza.validate_topping(i) for i in ingredients in the codes below? Thanks

class Pizza: def __init__(self, toppings): self.toppings = toppings @staticmethod def validate_topping(topping): if topping == "pineapple": raise ValueError("No pineapples!") else: return True ingredients = ["cheese", "onions", "spam"] if all(Pizza.validate_topping(i) for i in ingredients): pizza = Pizza(ingredients)

22nd Jan 2019, 6:14 PM
Jinxia Li
Jinxia Li - avatar
3 Antworten
+ 1
Hello, basically the function all() takes an iterable as argument and then will return true if all elements in the iterable are true or will return false if one or more elements of the iterable are false. In this case it will check for every value inside the “ingredients” if they are true or false calling the static method “validate_topping” of the class “Pizza”. Virtually would be something like this: if Pizza.validate_topping(cheese) is true then return true if Pizza.validate_topping(onions) is true then return true if Pizza.validate_topping(spam) is true then return true So in the expression all(Pizza.validate_topping(i) for i in ingredients) the variable i will be substituted by every value in the list ingredients. Then the method Pizza.validate_pizza will return true for everything except for pineapple. So if in the list ingredient, “pineapple” is not present it will return true so the condition “if” will evaluate true and the program will proceed forward! Hope my explanation is clear enough... Let me know!
23rd Jan 2019, 12:33 AM
Sekiro
Sekiro - avatar
0
Hi there, thanks for the answer. I understand that the all() method takes an iterable(list, tuple, or dictionary, etc.) as argument. So what is ( Pizza.validate_topping(i) for i in ingredients) considered? How can Pizza.validate(i) be put before the for loop(for i in ingredients)?
23rd Jan 2019, 2:05 AM
Jinxia Li
Jinxia Li - avatar
0
Hi, I found out the syntax I talked about, it's called Generator Expression which is similar to List Comprehension. Here is an article about both: https://medium.freecodecamp.org/JUMP_LINK__&&__python__&&__JUMP_LINK-list-comprehensions-vs-generator-expressions-cef70ccb49db 🍻
23rd Jan 2019, 3:29 AM
Jinxia Li
Jinxia Li - avatar