Chapter 2 Summary

A summary of loops and iteration in Python: indentation rules, while loops, control flow, range, built-in functions, sequences, for loops, and exploration tools.

Summary

This summary covers loops and iteration in Python: indentation and semicolon rules, while loops, control flow statements, the range function, built-in functions, sequences and iterables, for loops, and exploration tools.

Indentation and Semicolon Rules

Indentation

  • Python uses indentation (whitespace) to define code blocks instead of curly braces.
  • Indentation is part of the syntax, not just for readability.
  • All statements in the same block must have the same indentation level.
  • After a colon :, the next line must be indented.
  • Standard indentation is 4 spaces per level (tabs are discouraged).
if x > 5:
print("x is greater than 5") # Indented
print("This is also inside") # Same indentation
print("This is outside") # Not indented

Semicolons

  • Semicolons separate statements on the same line, they don’t terminate them.
  • Cannot separate a simple statement from a compound statement (like a loop).
  • Generally discouraged as it goes against Python’s readability philosophy.
x = 1; y = 2 # Valid: two simple statements
if x > 0: print(x); print(y) # Valid: simple statements in suite
print("Hello"); for i in range(5): print(i) # ERROR: cannot separate simple from compound

Simple vs Compound Statements

  • Simple statement: Executes as one unit (e.g., x = 5, print(x), break).
  • Compound statement: Contains other statements and controls a suite (e.g., if, while, for).
  • A suite can be either:
    • Indented block on new lines
    • Semicolon-separated simple statements on the same line

While Loops

Basic Syntax

while condition:
# loop body here
  • The condition is checked before each iteration.
  • Loop continues as long as the condition is True.
  • Must ensure the condition becomes False to avoid infinite loops.
i = 0
while i < 5:
print(i)
i += 1

Flags

  • A flag is a boolean variable that acts as an indicator or signal.
  • Used to control loop execution or track state.
running = True
total = 0
while running:
num = int(input("Enter a number: "))
if num < 0:
running = False
else:
total += num

Infinite Loops

  • A loop that runs forever (or without a bound).
  • Sometimes intentional: while True: with break inside.
  • Often a bug when the condition never becomes False.
while True:
password = input("Enter password: ")
if password == "correct":
break

Nested Loops

  • A loop inside another loop.
  • Inner loop completes fully for each iteration of the outer loop.
for i in range(2):
for j in range(3):
print("i=", i, ", j=", j, end="; ")
# Output: i=0, j=0; i=0, j=1; i=0, j=2; i=1, j=0; i=1, j=1; i=1, j=2;

Control Flow Statements

continue

  • Skips the remainder of the current iteration and moves to the next one.
  • Only affects the innermost loop when nested.
for i in range(10):
if i % 2 != 0:
continue
print(i)

break

  • Terminates the current loop immediately.
  • Only breaks out of the innermost loop when nested.
while True:
num = int(input("Enter a number: "))
if num < 0:
break
print(num)

else with Loops

  • The else clause executes only if the loop completes normally (without a break).
for i in range(2, n):
if n % i == 0:
print("Not prime")
break
else:
print("Prime")

Range

range(n) - One Argument

  • Generates numbers from 0 up to (but not including) n.
  • Produces n numbers: 0, 1, 2, ..., n-1.
list(range(5)) # [0, 1, 2, 3, 4]

range(start, end) - Two Arguments

  • Generates numbers from start (inclusive) up to (but not including) end.
list(range(2, 8)) # [2, 3, 4, 5, 6, 7]

range(start, end, step) - Three Arguments

  • Generates numbers starting from start, up to (but not including) end, incrementing by step.
list(range(0, 10, 2)) # [0, 2, 4, 6, 8]
list(range(1, 10, 2)) # [1, 3, 5, 7, 9]

Negative Step

  • When step is negative, the range counts backwards.
  • Start must be greater than end for the range to produce values.
list(range(10, 0, -1)) # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
list(range(20, 0, -2)) # [20, 18, 16, 14, 12, 10, 8, 6, 4, 2]

Some Built-in Functions

len()

  • Returns the number of items in an object.
len("Hello") # 5
len(range(5)) # 5
len(range(2, 10)) # 8

min() and max()

  • min() returns the smallest item; max() returns the largest.
  • With strings, compares based on Unicode values.
min("Hello") # 'H'
max("Hello") # 'o'
min(range(5, 15)) # 5
max(range(5, 15)) # 14

sum()

  • Adds all numbers in an iterable and returns the total.
sum(range(1, 6)) # 15
sum(range(0, 11, 2)) # 30

abs()

  • Returns the absolute value of a number.
abs(5) # 5
abs(-5) # 5
abs(0) # 0

pow()

  • pow(x, y) returns x raised to the power of y.
  • pow(x, y, z) returns (x ** y) % z (modular exponentiation).
pow(2, 3) # 8
pow(2, 3, 5) # 3

round()

  • Rounds a number to the nearest integer or specified decimal places.
round(3.7) # 4
round(3.14159, 2) # 3.14

chr() and ord()

  • ord(char) returns the Unicode code point of a character.
  • chr(code) returns the character for a Unicode code point.
ord('A') # 65
chr(65) # 'A'

id()

  • Returns the unique identifier (memory address) of an object.
  • Useful for understanding if two variables refer to the same object.

Sequences and Iterables

Sequences

  • Sequence: An ordered collection of items with specific positions (indices).
  • Types: strings, lists, tuples, range objects, bytes, bytearrays, buffers.
  • Characteristics:
    • Ordered: Items have specific positions (index starting from 0)
    • Indexable: Access items by position using [index]
    • Sliceable: Extract portions using slicing [start:end]
    • Length: Get number of items using len()
    • Iterable: Can be processed item by item

Iterables

  • Iterable: Any object that can produce items one at a time.
  • All sequences are iterables, but not all iterables are sequences.
  • Examples: sequences, sets, dictionaries, files, generators.

Common Sequence Operations

Indexing

  • Zero-based indexing: First item is at index 0.
  • Negative indexing: -1 is the last item, -2 is second-to-last, etc.
text = "Python"
text[0] # 'P'
text[-1] # 'n'
text[-2] # 'o'

Slicing

  • [start:end]: Extract portion from start (inclusive) to end (exclusive).
  • [start:end:step]: Extract with step size.
  • [::-1]: Reverse a sequence.
text = "Python"
text[0:3] # "Pyt"
text[2:] # "thon"
text[:4] # "Pyth"
text[::2] # "Pto"
text[::-1] # "nohtyP"

Membership Testing

"P" in "Python" # True
"x" not in "Python" # True

Concatenation and Repetition

"Hello" + " " + "World" # "Hello World"
"Hi" * 3 # "HiHiHi"

For Loops

Basic Syntax

for variable in sequence:
# loop body here
  • The variable takes each value from the sequence one at a time.
  • Automatically handles iteration—no need to manually increment or check conditions.
for i in range(5):
print(i) # Prints 0, 1, 2, 3, 4

Using range() with for loops

for i in range(5): # 0, 1, 2, 3, 4
for i in range(2, 8): # 2, 3, 4, 5, 6, 7
for i in range(1, 10, 2): # 1, 3, 5, 7, 9
for i in range(20, 0, -2): # 20, 18, 16, 14, 12, 10, 8, 6, 4, 2

For Loops vs While Loops

Use for loops when:

  • The number of iterations is known in advance.
  • Iterating over a sequence.
  • You want simpler, more readable code.

Use while loops when:

  • The number of iterations is unknown.
  • Complex condition logic is needed.
  • Repeating until an event occurs.

Control Flow with for loops

  • continue: Skip to next iteration.
  • break: Exit the loop.
  • else: Execute if loop completes normally (no break).
for i in range(10):
if i % 2 != 0:
continue # Skip odd numbers
print(i) # Print even numbers

Nested for loops

for i in range(3):
for j in range(3):
print("i=", i, "j=", j)

Exploring with dir() and help()

dir()

  • Returns a list of names (attributes and methods) available in an object.
  • Called without arguments: shows names in current scope.
  • Called with an object: shows attributes and methods of that object.
dir() # Names in current scope
dir("hello") # Methods available for strings

help()

  • Displays documentation (docstrings) for objects, functions, modules, or keywords.
  • Shows how to use something, while dir() shows what’s available.
help(print) # Documentation for print function
help("hello".upper) # Documentation for upper method
  • Use dir() to discover what’s available, then help() to learn how to use it.

Course Progress

Section 18 of 61

Back to Course