π Loops in Python#
Loops help your program repeat tasks automatically without writing the same code again and again. They are perfect for when you want to process lots of data, run a task multiple times, or iterate over collections! Letβs dive into the magic of loops. β¨
What Are Loops? π€#
Loops execute a block of code multiple times until a condition is met or for every item in a collection.
1. The while
Loop β³#
Repeats a block of code while a condition is true.
count = 1
while count <= 5:
print("Count is", count)
count += 1 # Increment count to avoid infinite loop
Important: Without changing the condition inside, a while
loop can run forever (infinite loop).
2. The for
Loop π#
Used for iterating over a sequence (like list, string, or range).
colors = ["red", "green", "blue"]
for color in colors:
print(color)
Often used with range()
to repeat a fixed number of times:
for i in range(5):
print("Iteration", i)
3. Loop Control Statements π#
break
β Immediately stops the loop.continue
β Skips the current iteration and moves to the next.else
with loops β Runs when loop finishes withoutbreak
.
for i in range(1, 6):
if i == 3:
continue # Skip printing 3
print(i)
else:
print("Loop finished!")
Practice Questions with Solutions π#
- Practice: Print numbers from 1 to 10 using a
while
loop.- Solution:
num = 1
while num <= 10:
print(num)
num += 1
- Practice: Print each character in the string “Python”.
- Solution:
for ch in "Python":
print(ch)
- Practice: Use a loop to sum all numbers from 1 to 5.
- Solution:
total = 0
for i in range(1, 6):
total += i
print("Sum:", total) # Output: 15
Step-by-Step Challenge: Guessing Game π―#
Ask the user to guess a secret number between 1 and 5 until they guess correctly.
secret = 3
guess = 0
while guess != secret:
guess = int(input("Guess the number (1-5): "))
if guess == secret:
print("You guessed it right! π")
else:
print("Try again!")
Checklist for This Chapter β #
- Used
while
loops to repeat with conditions - Used
for
loops to iterate over sequences - Controlled loops using
break
andcontinue
- Used
else
block in loops
You now have a powerful tool to automate repetitive tasks in Python. Keep practicing loops by creating games, calculators, and more! π