Week 2: Loops + Git Branching
A 6-day course covering Python loopsโfor, while, nested loops, break/continueโplus Git branching & merging.
Click any concept to jump directly to that section!
๐ Overview: Days 1โ5 cover Python loops with hands-on exercises and a mini-project. Day 6 introduces Git branching and merging for collaborative workflows. Each day includes concept explanations, live coding demos, student exercises, and solution discussions.
๐ Prerequisite: Week 1 (variables, data types, conditionals, basic Git).
๐ฏ Goal: By the end of this week, you'll automate repetitive tasks with loops, solve pattern problems, and manage parallel code versions with Git branches.
For Loops
range(), iterating lists/strings
While Loops
indefinite iteration, sentinels
Nested Loops
patterns, multiplication table
Break, Continue, else
loop control & loop-else
Mini-Project
Number Guessing Game
Git Branching
branch, checkout, merge
Day 1 For Loops & The range() Function
Learning Objectives: Understand why we use loops. Write for loops with range(). Iterate over strings and lists. Use loop variables effectively.
Click "Run" to see for i in range(1,7): iterate step by step.
The range() Function
for i in range(5): # 0 1 2 3 4
print(i)
for i in range(2, 7): # 2 3 4 5 6
print(i)
for i in range(1, 10, 2):# 1 3 5 7 9
print(i)
for i in range(10, 0, -1):# 10 9 8 ... 1
print(i)
Iterating Over Strings & Lists
name = "Python"
for char in name:
print(char)
fruits = ["apple", "mango", "banana"]
for fruit in fruits:
print(f"I like {fruit}")
๐งโ๐ป Exercise: Sum of First N Numbers
Ask the user for a number n. Calculate and print the sum of all numbers from 1 to n using a for loop.
n = int(input("Enter a number: "))
total = 0
for i in range(1, n + 1):
total += i
print(f"Sum of 1 to {n} is {total}")
Sum of 1 to 10 is 55
i takes each value from range() one at a time. range(1, n+1) is used because range excludes the stop value.Day 2 While Loops & Indefinite Iteration
Learning Objectives: Understand when to use while vs for. Write condition-based loops. Use sentinel values and counters. Avoid infinite loops.
While Loop Basics
count = 1
while count <= 5:
print(f"Count: {count}")
count += 1
๐ for loop
- Known number of iterations
- Iterating over sequences
- Example: print 1โ10
๐ while loop
- Unknown number of iterations
- Waiting for a condition
- Example: input validation
Sentinel-Controlled Loop
text = ""
while text != "quit":
text = input("Enter text (type 'quit' to stop): ")
if text != "quit":
print(f"You entered: {text}")
print("Goodbye!")
๐งโ๐ป Exercise: Countdown Timer
Ask the user for a starting number and print a countdown from that number to 1, then print "Blast off!" ๐
start = int(input("Enter countdown start: "))
while start > 0:
print(start)
start -= 1
print("๐ Blast off!")
5 4 3 2 1 ๐ Blast off!
False. Forgetting to update the counter is the most common cause. Show Ctrl+C to stop.Day 3 Nested Loops & Patterns
Learning Objectives: Place one loop inside another. Generate multiplication tables. Print star patterns. Understand how inner and outer loops interact.
Outer loop (i = 1..3), Inner loop (j = 1..3)
How Nested Loops Work
for i in range(1, 4):
for j in range(1, 4):
print(f"({i}, {j})", end=" ")
print()
Star Patterns
for i in range(1, 6):
print("*" * i) # right triangle
# Inverted:
for i in range(5, 0, -1):
print("*" * i)
i and j. Outer loop = rows, inner loop = columns. This mantra helps build any pattern.Day 4 Break, Continue & Loop-else
Learning Objectives: Exit loops early with break. Skip iterations with continue. Use the else clause with loops. Combine these with nested loops.
break
Exit the loop immediately
continue
Skip to next iteration
loop-else
Runs if no break occurred
break Example
for num in range(1, 200):
if num % 7 == 0 and num % 5 == 0:
print(f"Found: {num}") # 35
break
continue Example
for num in range(1, 11):
if num % 2 == 0:
continue
print(num) # 1 3 5 7 9
Loop-else (Prime Checker)
num = 29
for i in range(2, int(num**0.5)+1):
if num % i == 0:
print("Not prime"); break
else:
print("Prime")
else is unique to Python. It runs only if the loop finishes normally (no break), not if the loop didn't run at all.Day 5 Mini-Project: Number Guessing Game
Learning Objectives: Combine loops, conditionals, and user input into a complete game. Use random module. Give feedback. Track attempts.
Project Requirements
- Generate a random number between 1 and 100.
- Let the user guess until they get it right.
- After each guess, say "Too high!" or "Too low!".
- When correct, print the number of attempts.
- Bonus: Limit the user to 10 attempts.
import random
secret = random.randint(1, 100)
attempts = 0
while True:
guess = int(input("Your guess: "))
attempts += 1
if guess < secret: print("Too low!")
elif guess > secret: print("Too high!")
else: print(f"Correct! {attempts} attempts"); break
Day 6 Git: Branching & Merging
Learning Objectives: Understand why branches are used. Create and switch branches. Merge branches back together. Resolve basic merge conflicts.
Branching Commands
| Command | Purpose |
|---|---|
git branch | List branches |
git branch <name> | Create a new branch |
git checkout <name> | Switch to a branch |
git checkout -b <name> | Create and switch (shortcut) |
git merge <name> | Merge named branch into current |
git branch -d <name> | Delete a branch |
๐งโ๐ป Exercise: Create & Merge a Branch
Task: In your python-week1 repo, create a branch called improve-calc. Add modulo and exponent features to calculator.py. Commit, then merge into main.
cd python-week1
git checkout -b improve-calc
# Edit calculator.py ...
git add calculator.py
git commit -m "Added modulo and exponent"
git checkout main
git merge improve-calc -m "Merged improvements"
git branch -d improve-calc
Week 2 Practice Problems
Test your understanding with these problems covering all Week 2 concepts.
๐ฐ Beginner Level
1. Factorial Calculator
Problem: Ask for a number n and compute n! (factorial) using a for loop. Example: 5! = 5 ร 4 ร 3 ร 2 ร 1 = 120.
n = int(input("Enter a number: "))
factorial = 1
for i in range(1, n + 1):
factorial *= i
print(f"{n}! = {factorial}")2. Sum of Digits
Problem: Ask for an integer and calculate the sum of its digits using a while loop. Example: 1234 โ 1+2+3+4 = 10.
num = int(input("Enter an integer: "))
total = 0
temp = abs(num)
while temp > 0:
total += temp % 10
temp //= 10
print(f"Sum of digits = {total}")3. Hollow Square Pattern
Problem: Print a hollow square of * with side length n using nested loops.
n = 5
for i in range(n):
for j in range(n):
if i == 0 or i == n-1 or j == 0 or j == n-1:
print("*", end=" ")
else:
print(" ", end=" ")
print()โก Intermediate Level
4. Fibonacci Series
Problem: Print the first n Fibonacci numbers using a for loop. The series starts 0, 1, 1, 2, 3, 5, 8, 13, ...
n = int(input("How many Fibonacci numbers? "))
a, b = 0, 1
for _ in range(n):
print(a, end=" ")
a, b = b, a + b5. FizzBuzz (Classic Interview Question)
Problem: Print numbers 1 to 50. For multiples of 3 print "Fizz", for multiples of 5 print "Buzz", for multiples of both print "FizzBuzz".
for num in range(1, 51):
if num % 3 == 0 and num % 5 == 0:
print("FizzBuzz")
elif num % 3 == 0:
print("Fizz")
elif num % 5 == 0:
print("Buzz")
else:
print(num)Unsolved Exercises
Challenge yourself! Try these without peeking at solutions. All concepts are from Week 2.
๐ฐ Beginner
1. Reverse a String
Problem: Ask for a string and print it in reverse using a for loop (without using [::-1] slicing). Example: "hello" โ "olleh".
2. Count Vowels
Problem: Ask for a string and count how many vowels (a, e, i, o, u) it contains using a loop.
โก Intermediate
3. Diamond Pattern
Problem: Print a diamond shape with * using nested loops. The user provides the number of rows for the top half. Hint: combine an increasing triangle and a decreasing triangle.
4. ATM Withdrawal Simulator
Problem: Set an initial balance (e.g., โน5000). Use a while loop to let the user withdraw money. Validate: amount must be positive, must not exceed balance, and must be a multiple of 100. Print remaining balance. Add an exit option. Bonus: track total withdrawals.