
Have you ever wanted to go through something and do something with the things in it? No? Just me? Oh. Well, today we’re gonna cover just that.
Say for example you have a list of students, and you want to count how many students are within your list; we can do that with a for loop! For this example, we’ll use a python list where the elements will be names:
students = ["Monica", "Rachel", "Ross", "Chandler", "Joey", "Phoebe"]
With a for loop we can iterate through this and count the number of students:
count = 0
for item in students:
count = count + 1print(count)
The above will print out the number 6, because as our loop iterates through our list it will add 1 to our count. If we wanted to see this in action we could place an additional print()
statement within our loop and it would print out the count as it goes through!
count = 0
for item in students:
count = count + 1
print(count)print(count)//this will be printed from within our for loop
1
2
3
4
5
6
//this one is printed after our for loop has been completed
6
for loops are wonderful tools for counting, and this may be the most frequent use you see of them!
