Week 2: Loops + Git Branching

A 6-day course covering Python loopsโ€”for, while, nested loops, break/continueโ€”plus Git branching & merging.

๐Ÿงญ Week 2 Concept Map Overview

Click any concept to jump directly to that section!

๐Ÿ” for Loop โ†’ ๐Ÿ”„ while Loop โ†’ ๐Ÿชข Nested Loops โ†’ ๐Ÿ›‘ break/continue โ†’ ๐ŸŽฎ Mini-Project โ†’ ๐Ÿ”€ Git Branches

๐Ÿ“… 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.

Day 1

For Loops

range(), iterating lists/strings

Day 2

While Loops

indefinite iteration, sentinels

Day 3

Nested Loops

patterns, multiplication table

Day 4

Break, Continue, else

loop control & loop-else

Day 5

Mini-Project

Number Guessing Game

Day 6

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.

๐Ÿ“ How range(start, stop, step) Works Infographic
range(5)0,1,2,3,4
range(2,7)2,3,4,5,6
range(1,10,2)1,3,5,7,9
range(10,0,-1)10,9,8,...,1
๐Ÿ” Live For Loop Simulator Interactive

Click "Run" to see for i in range(1,7): iterate step by step.

1 2 3 4 5 6

The range() Function

day1_range.py
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

day1_iterate.py
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.

day1_exercise_solution.py
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}")
Enter a number: 10
Sum of 1 to 10 is 55
๐Ÿ’ก Instructor Tip: The loop variable 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

day2_while_basic.py
count = 1
while count <= 5:
    print(f"Count: {count}")
    count += 1
๐Ÿค” for vs while โ€” Decision Guide Infographic

๐Ÿ” 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

day2_sentinel.py
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!" ๐Ÿš€

day2_exercise_solution.py
start = int(input("Enter countdown start: "))
while start > 0:
    print(start)
    start -= 1
print("๐Ÿš€ Blast off!")
Enter countdown start: 5
5 4 3 2 1 ๐Ÿš€ Blast off!
โš ๏ธ Infinite Loop Alert: Always ensure the loop condition will eventually become 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.

๐Ÿงฉ Nested Loop Visualization (i=outer, j=inner) Interactive Grid

Outer loop (i = 1..3), Inner loop (j = 1..3)

How Nested Loops Work

day3_nested_basic.py
for i in range(1, 4):
    for j in range(1, 4):
        print(f"({i}, {j})", end=" ")
    print()

Star Patterns

day3_patterns.py
for i in range(1, 6):
    print("*" * i)   # right triangle
# Inverted:
for i in range(5, 0, -1):
    print("*" * i)
๐Ÿ’ก Instructor Tip: Draw a table tracing 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.

๐Ÿ›‘ Loop Control Commands Reference
๐Ÿ›‘

break

Exit the loop immediately

โญ๏ธ

continue

Skip to next iteration

๐Ÿ

loop-else

Runs if no break occurred

break Example

day4_break.py
for num in range(1, 200):
    if num % 7 == 0 and num % 5 == 0:
        print(f"Found: {num}")   # 35
        break

continue Example

day4_continue.py
for num in range(1, 11):
    if num % 2 == 0:
        continue
    print(num)   # 1 3 5 7 9

Loop-else (Prime Checker)

day4_loop_else.py
num = 29
for i in range(2, int(num**0.5)+1):
    if num % i == 0:
        print("Not prime"); break
else:
    print("Prime")
โš ๏ธ Note: Loop-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

  1. Generate a random number between 1 and 100.
  2. Let the user guess until they get it right.
  3. After each guess, say "Too high!" or "Too low!".
  4. When correct, print the number of attempts.
  5. Bonus: Limit the user to 10 attempts.
guessing_game.py
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
๐Ÿš€ Extension: Add difficulty levels, high score tracking, or hints when within 5.

Day 6 Git: Branching & Merging

Learning Objectives: Understand why branches are used. Create and switch branches. Merge branches back together. Resolve basic merge conflicts.

๐ŸŒฟ Git Branching Workflow Visual
๐Ÿ”ต main (stable)
โ†’
๐ŸŸ  feature-branch
โ†’
๐ŸŸข merge back

Branching Commands

CommandPurpose
git branchList 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.

terminal
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 + b
5. 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".

Write your solution here.
2. Count Vowels

Problem: Ask for a string and count how many vowels (a, e, i, o, u) it contains using a loop.

Write your solution here.

โšก 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.

Write your solution here.
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.

Write your solution here.