Loops
Loops
While loops are loops that keep doing something until a condition is met.
Result:
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Code:
i = 1 #Initialize the counter
while i < 11: #Set the limit
print(i) #Print the number
i += 1 #Increment the counter
Result:
1
2
3
4
5
6
7
8
9
10
Code:
i=1
total = 0
while i < 501:
total += 0
i += 1
Result:
The total is 125250
Code:
while True:
print("Hello World!")
Result:
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
.
.
.
For Loops:
Everything we have done so far can also be done with a for-loop. For loops are also sometimes a
lot more powerful than while loops.
Before we can use a for loop you have to understand the range function.
range(initial, end, stepSize = 1)
So initial is where you start from, end-1 is where you end (We dont count the end number. It is
end - 1.) The stepSize is what you go up by. It is usually 1 and you dont have to set it.
range(10, 100, 10) will give you: 10, 20, 30, 40, 50, 60, 70, 80, 90
Result:
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Result:
1
2
3
4
5
6
7
8
9
10
Result:
The total is: 125250.