Skip to main content

if-elif-else

if <condition>:
       <if body>
elif <second_condition>:
       <elif body>
elif <third_condition>:
       <elif body>
...
else:
       <else body>

Conditionally execute code. The elif and else blocks are optional.

Components:
if <condition>:
If the condition is True, the body of the if statement is executed. Condition will be checked even if another if condition is fulfilled.
elif <condition>:
If the if condition is False, code moves onto the elif statement and checks the condition. If an if statement was executed, the elif conditions will not be checked.
else <condition>:
If none of the if and elif conditions are met, the else body will execute.

pets = bpd.read_csv('pets.csv')
pets
IndexIDSpeciesColorWeightAge
0dog_001dogblack405
1cat_001catgolden1.50.2
2cat_002catblack159
3dog_002dogwhite802
4dog_003dogblack250.5
5ham_001hamsterblack13
6ham_002hamstergolden0.250.2
7cat_003catblack100
def more_descriptive_name(id_str, species, color, weight, age):
return id_str + ': This ' + color + ' ' + species + ' weighs ' + weight + ' lbs and is ' + age + ' years old'

def cat_and_dog_info(pet_id):
id_arr = np.array(pets.get('ID'))
if pet_id not in id_arr:
return 'This pet is not in our record'
pets_info = pets[pets.get('ID') == pet_id]
age = pets_info.get('Age').iloc[0]
weight = pets_info.get('Weight').iloc[0]
species = pets_info.get('Species').iloc[0]
color = pets_info.get('Color').iloc[0]
if (species == 'dog') and (age < 1.5):
return pet_id + ': This is a puppy 🐶'
elif (species == 'cat') and (age < 1):
return pet_id + ': This is a kitten 🐱'
elif (species == 'dog') or (species == 'cat'):
weight = str(weight)
age = str(age)
return more_descriptive_name(pet_id, species, color, weight, age)

else:
return pet_id + ': This pet is not a dog or a cat'
cat_and_dog_info('dog_001')

'dog_001: This black dog weighs 40.0 lbs and is 5.0 years old'

cat_and_dog_info('cat_001')

'cat_001: This is a kitten 🐱'

cat_and_dog_info('cat_009')

'This pet is not in our record'