Day 9: Loops in Python – Make Your Code Repeat Like a Boss!

 Day 9: Loops in Python – Make Your Code Repeat Like a Boss!

Heyy, Day 9 is here! You’ve already mastered Variables, Operators, Strings, Lists, Tuples, Sets, Dictionaries, and If-Else. Now, Day 9 is all about Loops – this is where your code starts repeating tasks automatically like a robot!

Think of it like:

Print 1 to 10 Check 100 emails Ask user until correct input

No more copy-pasting 100 times! Loops do the heavy lifting.


What Are Loops? (10 mins)

Two main types in Python:

LoopUse Case
for loopWhen you know how many times to repeat
while loopWhen you repeat until a condition is true


1. For Loop – The "Countable" Loop (15 mins)

python
# Print numbers 0 to 4
for i in range(5):
    print(i)

Output:

text
0
1
2
3
4

range(start, stop, step):

  • range(5) → 0 to 4
  • range(1, 6) → 1 to 5
  • range(0, 10, 2) → 0, 2, 4, 6, 8

Loop through a List:

python
fruits = ["apple", "banana", "orange"]

for fruit in fruits:
    print("I love", fruit)

Output:

text
I love apple
I love banana
I love orange

Try This: In day9.py:

python
# Count from 1 to 10
for num in range(1, 11):
    print(num)

# Print even numbers
print("Even numbers:")
for i in range(2, 11, 2):
    print(i)

2. While Loop – The "Condition" Loop (15 mins)

python
count = 1
while count <= 5:
    print("Count:", count)
    count += 1  # Important! Without this → infinite loop!

Output:

text
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

Use break to exit early:

python
password = ""
while password != "secret":
    password = input("Enter password: ")
    if password == "secret":
        print("Access granted!")
        break
    else:
        print("Wrong! Try again.")

Loop Controls: break, continue, else

ControlWhat it does
breakExit loop immediately
continueSkip rest of current loop, go to next
elseRuns if loop completed normally (no break)
python
for i in range(1, 6):
    if i == 3:
        continue  # Skip 3
    if i == 5:
        break     # Stop at 5
    print(i)
else:
    print("Loop finished without break!")

Output:

text
1
2
4

Mini Project: Number Guessing Game (30–40 mins)

Let’s build a Number Guessing Game!

  • Computer picks a secret number (1–100)
  • User guesses
  • Give hints: "Too high", "Too low"
  • Count attempts
  • Win when correct!

Code (day9_guess.py):

python
import random

print("=== Number Guessing Game ===")
secret = random.randint(1, 100)
attempts = 0
max_attempts = 7

print(f"I'm thinking of a number between 1 and 100. You have {max_attempts} attempts!")

while attempts < max_attempts:
    guess = int(input("Your guess: "))
    attempts += 1
    
    if guess == secret:
        print(f"Correct! You got it in {attempts} attempts!")
        break
    elif guess < secret:
        print("Too low!")
    else:
        print("Too high!")
    
    remaining = max_attempts - attempts
    if remaining > 0:
        print(f"{remaining} attempts left.")
    else:
        print(f"Game Over! The number was {secret}.")

Run & Play:

text
=== Number Guessing Game ===
I'm thinking of a number between 1 and 100. You have 7 attempts!
Your guess: 50
Too low!
6 attempts left.
Your guess: 75
Too high!
5 attempts left.
Your guess: 62
Correct! You got it in 3 attempts!

Bonus: Nested Loops (Star Pattern)

python
for i in range(1, 6):
    for j in range(i):
        print("*", end="")
    print()  # New line

Output:

text
*
**
***
****
*****

Common Mistakes & Fixes

MistakeErrorFix
No count += 1Infinite loopAlways update counter
range(5) → 0–4Off-by-oneRemember stop is exclusive
input() without int()ValueErrorConvert user input


Day 9 Wrap-Up

You learned:

  • for loop with range() and lists
  • while loop with condition
  • break, continue, else
  • Built a Number Guessing Game
  • Used random module

Track Progress:

Day 9 Done: Loops are magic! Built guessing game. Doubt: for vs while? Answer: Use for when count is known, while when condition-based.

Resources:

Comments

Post a Comment

Popular Posts