⬅ Previous Topic
Truthy and Falsy ValuesNext Topic ⮕
Loop Control Statements - break, continue, pass⬅ Previous Topic
Truthy and Falsy ValuesNext Topic ⮕
Loop Control Statements - break, continue, passLoops are used to execute a block of code repeatedly as long as a given condition is true. They help reduce code duplication and are essential in tasks like traversing arrays, repeating calculations, or processing input.
Let’s print numbers from 1 to 5 using a for loop.
for i = 1 to 5:
print(i)
1 2 3 4 5
The loop starts at 1 and increments i
by 1 until it reaches 5. Each time, the value of i
is printed.
What happens if we change the condition to go from 5 to 1?
You need to decrement i
instead of incrementing:
for i = 5 to 1 step -1:
print(i)
5 4 3 2 1
This loop continues while a condition is true.
i = 1
while i <= 5:
print(i)
i = i + 1
1 2 3 4 5
The loop starts with i = 1
. Each iteration increases i
by 1. When i
becomes 6, the condition i <= 5
is false, and the loop exits.
What if we forget to increment i
?
The loop will never end, resulting in an infinite loop. Always ensure there's a termination condition being met.
This loop executes at least once, even if the condition is false.
i = 10
do:
print(i)
i = i + 1
while i <= 5
10
Even though the condition is false at the start, the loop body runs once before checking it.
Loops inside loops are called nested loops. These are useful for working with 2D data like grids or matrices.
for i = 1 to 3:
for j = 1 to 2:
print("i =", i, ", j =", j)
i = 1 , j = 1 i = 1 , j = 2 i = 2 , j = 1 i = 2 , j = 2 i = 3 , j = 1 i = 3 , j = 2
for
loops when the number of iterations is knownwhile
loops when the condition is evaluated dynamicallydo while
loops to ensure the code block runs at least onceQ: How many times will the following loop run?
i = 1
while i < 4:
print(i)
i = i + 1
A: It will print 1, 2, and 3 — 3 times in total.
⬅ Previous Topic
Truthy and Falsy ValuesNext Topic ⮕
Loop Control Statements - break, continue, passYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.