🔁

Understanding For Loops in Python

Apr 24, 2025

Lecture on For Loops in Python

Overview

  • A for loop executes a block of code a fixed number of times.
  • Commonly used to iterate over ranges, strings, sequences, or anything iterable.
  • For loops are ideal when you know the exact number of iterations needed.

Basic Syntax

  • Structure: for variable in iterable:
    • variable: Counter or iterator, can be named anything (e.g., x, counter).
    • iterable: Can be a range, string, etc.
  • Indent the code block under the for loop to specify the code to repeat.

Example: Counting to Ten

  • Code: for x in range(1, 11): print(x)
  • Explanation:
    • range(1, 11): Starts at 1, ends before 11, effectively counting to 10.
    • Prints numbers 1 through 10.

Counting Backwards

  • Use the reversed() function with range.
  • Code: for x in reversed(range(1, 11)): print(x) print("Happy New Year")
  • Explanation:
    • Counts from 10 to 1.
    • Prints "Happy New Year" after loop, indicating exiting the loop.

Counting with Steps

  • Use an additional parameter for step size in range().
  • Code: for x in range(1, 11, 2): print(x)
  • Explanation:
    • Uses a step of 2, printing 1, 3, 5, 7, 9.

Iterating Over Strings

  • For loops can iterate over characters in a string.
  • Example: credit_card = "1234-5678" for x in credit_card: print(x)
  • Explanation:
    • Prints each character of the credit_card string, including dashes.

Useful Keywords: continue and break

Continue

  • Skips the current iteration of the loop.
  • Example: for x in range(1, 21): if x == 13: continue print(x)
  • Explanation:
    • Skips number 13 while printing numbers 1 to 20.

Break

  • Exits the loop entirely.
  • Example: for x in range(1, 21): if x == 13: break print(x)
  • Explanation:
    • Stops the loop at number 12, not printing 13 or any numbers after.

Comparison with While Loops

  • While loops are better suited for scenarios where the number of iterations isn't known beforehand (potentially infinite tasks).

Conclusion

  • For loops are versatile and can handle iterations over any iterable.
  • Useful for tasks with a known repeat count or iterating over collections like strings.