Loops
Loops help us repeat actions in Python. Imagine telling the computer: "Do this again and again." That’s what loops are for!
Loops help us repeat actions in Python. Imagine telling the computer: "Do this again and again." That’s what loops are for!
Let’s say you want to print "Hi!" five times. Without a loop, you’d write:
print("Hi!")
print("Hi!")
print("Hi!")
print("Hi!")
print("Hi!")
Hi!
Hi!
Hi!
Hi!
Hi!
That works… but what if you wanted to print it 100 times? That’s where loops save time.
for Loop
A for loop is useful when you know in advance how many times you want to repeat a block of code. It’s commonly used to iterate over sequences like lists, strings, or ranges of numbers.
for variable in sequence:
# code to run for each item in the sequence
for: The loop keyword that starts the iteration.variable: A temporary variable that takes the value of each item in the sequence, one at a time.in: A keyword that links the loop variable with the sequence to iterate over.sequence: Any iterable object like range(), a list, or a string.
for i in range(5):
print("Hi!")
Hi!
Hi!
Hi!
Hi!
Hi!
range(5) generates a sequence of numbers from 0 to 4 (5 numbers in total).i takes on each of those values — first 0, then 1, and so on up to 4.i, the line print("Hi!") is executed once."Hi!" is printed 5 times.while Loop
A while loop in Python is used to repeatedly execute a block of code as long as a specified condition remains True.
while condition:
# code to repeat
while: The keyword that starts the loop.condition: An expression that is evaluated before each iteration. The loop runs as long as this condition is True.:: Indicates the start of the loop block.
count = 1
while count <= 3:
print("Welcome!")
count = count + 1
Welcome!
Welcome!
Welcome!
count is initialized to 1.count <= 3 is checked before each iteration.True, the loop body runs — printing "Welcome!" and then increasing count by 1.count = 1, 2, and 3.count becomes 4, the condition count <= 3 becomes False, so the loop stops.
A for loop in Python can be used to iterate over elements in a list — executing a block of code once for each item.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
apple
banana
cherry
fruits is defined with three string elements: "apple", "banana", and "cherry".for loop goes through each element in the list one by one.fruit holds the current list item.fruit.break stops the loop early.
for i in range(5):
if i == 3:
break
print(i)
0
1
2
i becomes 3, the break line runs and stops the loop.continue skips the rest of the loop for that time only.
for i in range(5):
if i == 2:
continue
print(i)
0
1
3
4
i is 2, it skips print(i).