Back to Sessions

Session 4

2 lessons completed

For Loops

Completed

Assignment

Write a for loop in print_numbers that logs the numbers 0-199 to the console.

Solution

def print_numbers():
    for i in range(0, 200):
        print(i)

Concept

for loop syntax, range(), indentation as loop body, printing values inside loops

How it went

Correct first time. Clean for loop with the right range (0, 200) to print 0–199.

Ratings

Concept grasp: Solid
Independent attempt: Good
Clean code: Good

Key takeaways

  • range(0, 200) gives you 0 to 199 — end is exclusive. Always double-check your range boundaries

Range Continued

Completed

Assignment

Fix the for loop in count_down. It takes start and end inputs where start > end. Use a negative step to print every integer counting down from start (inclusive) to end (exclusive).

Solution

def count_down(start, end):
    for i in range(start, end, -1):
        print(i)

Concept

Step parameter in range(), counting up by custom increments, counting down with negative step

How it went

Had the right idea (negative step) from the start. Had a syntax error on first attempt, resolved it, and the fix was minimal and clean.

Ratings

Concept grasp: Solid
Independent attempt: Good — knew the answer, syntax tripped him up briefly
Final solution: Clean and correct

Key takeaways

  • range(0, 10, 2) = 0, 2, 4, 6, 8. When counting down, step must be negative: range(10, 0, -1) gives 10, 9, 8...1
  • for vs while: use for when you know how many times to loop, while when you loop until something changes