Checking that a list is not empty
- check if some lists are empty before using a for loop
- if the pizza has no toppings, you can prompt the customer with a message
requested_toppings = []
if requested_toppings:
….for requested_topping in requested_toppings:
……..print(f”Adding {requested_topping}.”)
….print(“\nFinished making your pizza!”)
else:
….print(“Are you sure you want a plain pizza?”)
- this time we start with an empty list of requested toppings
- instead of using a for loop, we do a quick check
- if the name of a list is used in an if statement, Python returns True unless the list is empty, in which case it returns False
- Since the conditional test failed, we double check with the customer
Are you sure you want a plain pizza?
Using multiple lists
- people will ask for anything, like fries on a pizza
- use lists and if statements to make sure your input makes sense
- can define two lists, first is a list with available toppings, second is a list of requested toppings
- the latter is checked against the first before being added to the pizza
available_toppings = [‘mushrooms’, ‘olives’, ‘green peppers’, ‘pepperoni’, ‘pineapple’, ‘extra cheese’]
requested_toppings = [‘mushrooms’, ‘french fries’, ‘extra cheese’]
for requested_topping in requested_toppings:
….if requested_topping in requested_toppings:
……..print(f”Adding {requested_topping}.”)
….else:
……..print(f”Sorry, we don’t have {requested_topping}.”)
print(“\nFinished making your pizza!”)
- the defined list of available toppings could also be a tuple if toppings are set
Adding mushrooms.
Sorry, we don’t have french fries.
Adding extra cheese.
Finished making your pizza!
Styling your if statements
- Only recommendation PEP 8 provides for conditional tests is to use a single space around comparison operators, such as ==, >=, and <=
if age < 4:
- is better than:
if age<4:
- spacing doesn’t affect how Python reads your code, it just makes your code easier to read
Summary
- learned how to write conditional tests, which always evaluate to True or False
- learned how to write simple if statements, if-else chains, and if-elif-else chains
- used structures to identify particular conditions you need to test and to know when conditions have been met
- learned to handle certain items in a list differently than all other items while utilizing the efficiency of a for loop
- revisited Python’s style recommendations to ensure your code is easy to read