for-loops
for <loop variable> in <sequence>:
<loop body>
Performs the loop body for every element of the sequence.
- Components:
- loop variable : variable
- Variable that will take on the value of every element in the sequence at some point in the loop. Any valid variable is acceptable.
- sequence : iterable object
- e.g. Arrays, Lists, Strings
- loop body :
- Code to be executed for every element in sequence.
- Results:
- Output of loop body
pets
| Index | ID | Species | Color | Weight | Age | Is_Cat | Owner_Comment |
|---|---|---|---|---|---|---|---|
| 0 | dog_001 | dog | black | 40 | 5 | False | There are no bad dogs, only bad owners. |
| 1 | cat_001 | cat | golden | 1.5 | 0.2 | True | My best birthday present ever!!! |
| 2 | cat_002 | cat | black | 15 | 9 | True | ****All you need is love and a cat.**** |
| 3 | dog_002 | dog | white | 80 | 2 | False | Love is a wet nose and a wagging tail. |
| 4 | dog_003 | dog | black | 25 | 0.5 | False | Be the person your dog thinks you are. |
| 5 | ham_001 | hamster | black | 1 | 3 | False | No, thank you! |
| 6 | ham_002 | hamster | golden | 0.25 | 0.2 | False | No, thank you! |
| 7 | cat_003 | cat | black | 10 | 0 | True | No, thank you! |
for i in np.arange(pets.shape[0]):
chosen_pet = pets.iloc[i]
pet_id = chosen_pet.get('ID')
species = chosen_pet.get('Species')
age = chosen_pet.get('Age')
weight = chosen_pet.get('Weight')
print("This is a " + species + " with pet id " + str(pet_id) +', age ' + str(age) +', and weight '+str(weight))
This is a dog with pet id dog_001, age 5.0, and weight 40.0
This is a cat with pet id cat_001, age 0.2, and weight 1.5
This is a cat with pet id cat_002, age 9.0, and weight 15.0
This is a dog with pet id dog_002, age 2.0, and weight 80.0
This is a dog with pet id dog_003, age 0.5, and weight 25.0
This is a hamster with pet id ham_001, age 3.0, and weight 1.0
This is a hamster with pet id ham_002, age 0.2, and weight 0.25
This is a cat with pet id cat_003, age 0.0, and weight 10.0
np.append() · np.arange() · [Writing Functions](../Functions/Writing Functions.md) · if / elif / else
Problems or suggestions about this page? Fill out our feedback form.