IF statements

Python basics

Python
Basics
Author

Kunal Khurana

Published

October 6, 2023

Learning outcmoes

  1. write conditional tests, which always evaluate to True or False.
  2. write simple if statements, if-else chains, and if-elif-else chains.
  3. use these structures to identify particular conditions you needed to test and to know when those conditions have been met in your programs.
  4. learn to handle certain items in a list differently than all other items while continuing to utilize the efficiency of a for loop.

allowing a user to post a comment

banned_users = ['raghav', 'sunita', 'carlos']
user = 'dave'

if user not in banned_users:
    print(f"{user.title()}, you can post a comment if you wish.")
Dave, you can post a comment if you wish.

voting using if/else

age = 19

if age >= 18:
    print('You are old enough to vote!')
    print('Are you registered to vote?')
else:
    print("Sorry, you are too young to vote.")
    print("PLease register to vote as soon as you turn 18!")
    
You are old enough to vote!
Are you registered to vote?

price using if/else/elif

age = 12

if age < 4:
    price = 0
elif age < 18:
    price = 25
elif age <= 65:
    price = 40
else:
    price = 20
    
print(f"Your admission price is {price}.")
Your admission price is 25.
age = 66

if age < 4:
    price = 0
elif age < 18:
    price = 25
elif age <= 65:
    price = 40
else:
    price = 20
    
print(f"Your admission price is {price}.")
Your admission price is 20.

toppings using if/elif/else and for loops

req_toppings = ['mushrooms', 'green peppers', 'belpeppers', 'onions', 'lettuce']

for req_topping in req_toppings:
    if req_topping == 'onions':
        print("Sorry, we are out of onions right now.")
    else:
        print(f'Adding {req_topping}.')
    
print('\nFinished making your pizza!')
Adding mushrooms.
Adding green peppers.
Adding belpeppers.
Sorry, we are out of onions right now.
Adding lettuce.

Finished making your pizza!
req_toppings = []

if req_toppings:
    for req_topping in req_toppings:
         print(f'Adding {req_topping}.')
    print('\nFinished making your pizza!')
else:
    print("Are you sure you want a plain pizza?")
Are you sure you want a plain pizza?
available_toppings = ['mushrooms', 'mayo', 'south-west', 'green peppers', 'belpeppers', 'lettuce']
req_toppings = ['mushrooms', 'green peppers', 'broccoli']

for req_topping in req_toppings:  #we iterate over req_toppings
    if req_topping in available_toppings:
        print(f"Adding {req_topping}")
    else:
        print(f"Sorry, we don't have {req_topping}.")
        
print("\nFinished making your pizza!")
Adding mushrooms
Adding green peppers
Sorry, we don't have broccoli.

Finished making your pizza!