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