Skip to main content

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
IndexIDSpeciesAgeWeight
0dog_001dog540
1cat_001cat0.21.5
2cat_002cat915
3dog_002dog280
4dog_003dog0.525
5ham_001hamster31
6ham_002hamster0.20.25
7cat_003cat010
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