Loops and functions
Loops repeat work and functions package it into reusable pieces. Together they let short programs do large amounts of work clearly.
for loops
A for loop runs once for each item in a sequence: for name in ["Ana", "Ben"]: print(name). range() produces sequences of numbers: range(5) gives 0, 1, 2, 3, 4; range(1, 6) gives 1 to 5; range(0, 10, 2) gives even numbers below 10. Note the end value is excluded.
while loops
A while loop repeats as long as its condition is True: while balance < target: balance = balance * 1.05; years += 1. Something inside the loop must eventually make the condition False, or the loop runs forever. while loops suit situations where you do not know in advance how many repetitions are needed.
break and continue
break exits a loop immediately, for example when a search finds its target. continue skips the rest of the current iteration and moves to the next. Python loops can also have an else clause that runs only if the loop finished without break, which is handy for 'not found' messages.
Defining functions
def defines a function: def area(width, height): return width * height. width and height are parameters; calling area(3, 4) passes arguments and returns 12. A function without a return statement returns None. Functions should do one clear job and have descriptive names.
Default and keyword arguments
Parameters can have defaults: def greet(name, greeting="Hello"): return f"{greeting}, {name}!". greet("Ana") gives "Hello, Ana!" and greet("Ana", greeting="Hi") gives "Hi, Ana!". Keyword arguments, named at the call, make calls clearer and allow any order.
Scope
Variables created inside a function are local: they exist only during that call and do not affect variables with the same name outside. Variables defined at the top level of a file are global. Functions should usually receive data through parameters and send results back with return, rather than changing globals.
Docstrings and modules
A docstring is a string at the start of a function describing what it does, shown by help(). Related functions can be grouped in a module, a .py file, and imported elsewhere: import math gives math.sqrt and math.pi. Python's standard library includes modules for random numbers, dates, files, and much more.
Worked example
def is_prime(n): if n < 2: return False; for d in range(2, int(n ** 0.5) + 1): if n % d == 0: return False; return True. Checking divisors only up to the square root is enough, because any factor larger than the square root pairs with a smaller one. [n for n in range(20) if is_prime(n)] gives [2, 3, 5, 7, 11, 13, 17, 19].
Key takeaways
for loops iterate over sequences; range(a, b, step) excludes its end value. while loops repeat while a condition holds; ensure it eventually becomes False. break exits a loop; continue skips to the next iteration. def defines functions with parameters and return values; no return means None. Defaults and keyword arguments add flexibility. Local variables live only inside a function. Docstrings document functions; modules group code for import.
Flashcard
Repeats for each item in a sequence
Check your understanding
What numbers does range(2, 11, 3) produce?
