Loops
No account is required. Learn the material, try the examples, and mark it complete when you are ready to move on. Sign in with email only if you want to save progress across devices.
For loop
Now we are ready to learn a simple for loop.
Lets imagine if our object was to print a same thing 5 times. We would have to in this case write print function 5 times, right?
4 in range(5)Truefor i in range(5):
print("Hello. THe value of i is: {}".format(i))Hello. THe value of i is: 0
Hello. THe value of i is: 1
Hello. THe value of i is: 2
Hello. THe value of i is: 3
Hello. THe value of i is: 4
"Tickles what was that sorcery"
This is the ability of loops to repeat tasks.
To understand this, let's look at a simple example first.
Our problem statement is to print individual elements inside a list one by one.
list1 = [10,20,30,40]
list1[10, 20, 30, 40]We could use the print function 4 times here keeping in mind the appropriate indexes for the list elements
print(list1[0])
print(list1[1])
print(list1[2])
print(list1[3])10
20
30
40
But if the list contained say 20 elements, would you still be willing to print all elements one by one? No right.
In that case, we start a for loop with.
for i in list1
list1 = [1,2,4,7]for i in list1:
print(i)1
2
4
7
When python sees the keyword for, python starts a for loop, then python sees this "in" keyword.
Remember the in keyword?
10 in list1Truefor i in [1, 2, 3]:
print(i)1
2
3
With this code, python started a loop, initiated
# When we write
# for i in range(5):
# Python starts a loop (for loop) for i in range(5): # This will produce 5 True boolean
print(i) # i will be printed 5 times0
1
2
3
4
While loops
# Current value of i
print(i)4
counter = 10
while counter > 2:
# print(f"The current value of i: {counter}")
print(f"counter is greater than 2 and the value of counter is: {counter}")
# Now it will cause a infinite loop
# So we will decrease the value of counter
counter = counter - 1counter is greater than 2 and the value of counter is: 10
counter is greater than 2 and the value of counter is: 9
counter is greater than 2 and the value of counter is: 8
counter is greater than 2 and the value of counter is: 7
counter is greater than 2 and the value of counter is: 6
counter is greater than 2 and the value of counter is: 5
counter is greater than 2 and the value of counter is: 4
counter is greater than 2 and the value of counter is: 3
Finished this lesson?
Keep your place here, or save it across devices with an email link.
Saved in this browser. Save progress with email →