Control Structures and Functions
Control Structures and Functions tests selection, iteration and user-defined functions: if/elif/else, while, for with range(), loop control, parameter passing, return values and scope.
Core rules
- Python uses indentation, not braces, to define blocks. Inconsistent indentation is a syntax or logic error.
if/elif/elsetests conditions in order and runs the first true branch only.foriterates over a sequence;range(start, stop, step)excludesstop. With one argument, it starts at 0.whilerepeats while its condition remains true; ensure something changes inside the loop.breakexits the nearest loop,continueskips to the next iteration, andpassdoes nothing.- A loop's
elseblock runs only if the loop finished withoutbreak. defcreates a function. Parameters can be positional, keyword or default. A function withoutreturnreturnsNone.- Variables assigned inside a function are local unless declared
global.
Worked example
def greet(name, msg='Hello'):
return msg + ', ' + name
print(greet('Ravi'))
print(greet('Ravi', 'Hi'))
The first call uses the default msg, so it prints Hello, Ravi. The second passes 'Hi' positionally, overriding the default, so it prints Hi, Ravi. The function returns a string; it does not print inside itself, so the print() calls are required.
Traps that cost marks
- Forgetting that
range(1, 5)produces 1, 2, 3, 4, not 5. - Using
=instead of==in a condition. - Placing
returninside a loop when the final result is needed after the loop. - Assuming a local variable changes the global variable of the same name.
- Ignoring the colon after
if,for,whileanddef.