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
Index | ID | Species | Color | Weight | Age |
---|---|---|---|---|---|
0 | dog_001 | dog | black | 40 | 5 |
1 | cat_001 | cat | golden | 1.5 | 0.2 |
2 | cat_002 | cat | black | 15 | 9 |
3 | dog_002 | dog | white | 80 | 2 |
4 | dog_003 | dog | black | 25 | 0.5 |
5 | ham_001 | hamster | black | 1 | 3 |
6 | ham_002 | hamster | golden | 0.25 | 0.2 |
7 | cat_003 | cat | black | 10 | 0 |
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'