Python 3 Control Flow, Functions, Classes and Error Handling – Study Notes
offline

Source: Python Ultimate Cheat Sheet / Python 3 Cheat Sheet / Python for Data Science Cheat Sheet


Difficulty: Intermediate | Prerequisites: Python 3 Fundamentals and Data Structures study notes.


Big Picture

With data types and containers in hand, you now need to control what your program does and when. Conditional statements let code branch based on conditions, loops let it repeat, functions let you package reusable logic, and classes let you model real-world objects. Error handling keeps your program from crashing when something unexpected happens. These are the structural building blocks of every non-trivial Python program.


TL;DR

Use if/elif/else to branch, for to iterate over sequences, while to loop on a condition, def to define functions, class to define objects, and try/except to handle errors. Indentation (4 spaces) defines every block.


Key Terms

Conditional statement (if/elif/else)

A block of code that runs only when a specified condition is True. elif tests additional conditions; else catches everything remaining.

Think of it as a series of gates: Python checks each one in order and walks through the first open gate.

for loop

A loop that iterates over each item in a sequence (list, tuple, string, range, etc.) and executes a block for every item.

In simple terms, "do this once for every item in the collection."

while loop

A loop that keeps executing its block as long as a boolean condition remains True.

Think of it as "keep going until I say stop." You must change the condition variable inside the loop, or it runs forever.

break

A statement that immediately exits the innermost loop it sits in.

continue

A statement that skips the rest of the current iteration and jumps to the next one.

range()

A built-in function that produces an immutable sequence of integers. range(5) gives 0, 1, 2, 3, 4. range(start, end, step) for more control.

Function (def)

A named, reusable block of code defined with def function_name(parameters):. It can accept inputs (parameters) and return an output (return value).

Think of it as a small machine: data goes in, processing happens, a result comes out.

return

The statement that sends a value back from a function to whoever called it. If omitted, the function returns None.

Class

A blueprint for creating objects. Defined with class ClassName:. Contains attributes (data) and methods (functions that belong to the object).

In simple terms, a class is a template, and an object is a thing made from that template.

init

The constructor method that Python calls automatically when you create a new object from a class. It initialises the object's attributes.

self

The conventional name for the first parameter of every method in a class. It refers to the specific object instance the method is being called on.

Exception

An error that occurs during program execution. Python has built-in exception types like TypeError, ValueError, KeyError, IndexError.

try/except

A construct for catching and handling exceptions so the program does not crash. Code that might fail goes in the try block; recovery code goes in one or more except blocks.

Module

A .py file containing Python code (functions, classes, variables) that can be imported into other files with import.


Core Content

Conditional Statements

Python uses indentation (4 spaces) to define blocks, not braces.

if age <= 18:
    state = "Kid"
elif age > 65:
    state = "Retired"
else:
    state = "Active"

You can chain as many elif branches as you need. Only the first true condition's block runs. else is optional.

Nested if statements place one conditional inside another's block. The pass keyword fills an empty block so it does not cause a syntax error.

The not keyword inverts a condition: if x not in my_list: checks absence.

For Loops

A for loop iterates over any sequence:

for c in "Some text":
    if c == "e":
        cnt = cnt + 1

Use range() when you need index access:

  • range(5) produces 0, 1, 2, 3, 4.

  • range(2, 12, 3) produces 2, 5, 8, 11.

  • range(20, 5, -5) produces 20, 15, 10.

for idx, val in enumerate(lst): gives both index and value simultaneously.

While Loops

A while loop runs as long as its condition is True:

i = 1
while i <= 100:
    s = s + i**2
    i = i + 1

You must change the condition variable inside the loop. Forgetting this creates an infinite loop.

Loop Control

  • break exits the loop immediately.

  • continue skips to the next iteration.

  • An else block after a for or while runs only if the loop completes without hitting break.

Functions

Define with def, call with parentheses:

def fct(x, y, z):
    """documentation"""
    res = x + y + z
    return res

r = fct(3, 4, 5)

Parameters and variables inside a function are local to that function.

Default values: def fct(x, y, z, a=3, b=5): lets you omit a and b when calling.

Keyword arguments: product_info(productname="Jeans", price=45) lets you pass arguments in any order.

Variable-length arguments: *args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict.

A function that does not explicitly return a value returns None.

Classes and Objects

A class is a blueprint; an object is an instance of that class:

class car(object):
    def __init__(self, color, doors, tires):
        self.color = color
        self.doors = doors
        self.tires = tires

    def brake(self):
        return "Braking"

    def drive(self):
        return "I'm driving!"

__init__ is the constructor. self refers to the instance being created or used.

Subclasses inherit from a parent class: class Car(Vehicle): creates a Car that inherits everything from Vehicle and can override specific methods.

Exception Handling

Common built-in exceptions:

  • TypeError for wrong type operations (e.g. adding a string and an int).

  • ValueError for wrong value (e.g. int("abc")).

  • KeyError for missing dictionary key.

  • IndexError for out-of-range sequence index.

  • NameError for undefined variable.

  • ZeroDivisionError for dividing by zero.

  • ImportError for failed imports.

  • SyntaxError for invalid Python syntax.

Handling with try/except:

try:
    value = my_dict["d"]
except KeyError:
    print("That key does not exist!")

You can catch multiple exception types with separate except blocks. A bare except: catches everything (use sparingly). An else block after except runs if no error occurred. A finally block runs regardless.

Raising exceptions: raise ExcClass("message") signals an error intentionally.

File I/O

Open, read/write, close:

f = open("file.txt", "w", encoding="utf8")
f.write("coucou")
f.close()

Modes: 'r' read, 'w' write (overwrites), 'a' append. Add 'b' for binary.

Reading: f.read() reads everything, f.readline() reads one line, f.readlines() returns a list of lines.

Best practice is the with statement, which closes the file automatically:

with open("file.txt") as f:
    for line in f:
        # process each line

Modules and Imports

  • import math imports the whole module. Access via math.sqrt(81).

  • from math import sqrt, pi imports specific names directly.

  • import numpy as np renames for convenience.

  • Modules are searched in the directories listed in sys.path.


Real-World Applications

Conditional logic drives every decision a program makes, from validating user input to routing web requests. Loops power batch processing, data analysis pipelines, and anything that works through a collection of items. Functions are the primary unit of code reuse in every professional codebase. Classes underpin frameworks like Django and Flask, and exception handling is what separates a script that crashes from a program that recovers gracefully.


Common Misconceptions

  • Students often think elif is optional between if and else. It is optional, but without it you can only test one condition before falling through to else. Chaining elif lets you test many conditions in sequence.

  • Students often forget to update the loop variable in a while loop. This creates an infinite loop. Always check that something inside the block moves the condition toward False.

  • Students often think return and print do the same thing. They do not. print displays text on screen; return sends a value back to the calling code. A function can return without printing, and print without returning.

  • Students often think a bare except: is good practice. It is not. Catching every exception hides bugs. Catch specific types so you know exactly what you are handling.


Why It Matters / Exam Flags

⚠️ Be able to trace if/elif/else chains. Only the first true branch executes, then Python skips the rest.

⚠️ for loop with range(len(lst)) vs for val in lst vs for idx, val in enumerate(lst): know when to use each.

⚠️ Understand variable scope: a variable created inside a function does not exist outside it. This trips up many students in debugging questions.

⚠️ __init__ and self are tested frequently. Know that self.x = x stores the parameter as an attribute of the object.

⚠️ try/except/else/finally order matters. else runs only if no exception occurred. finally always runs.


Quick Self-Test

  1. True or False: In Python, blocks are defined by curly braces {}. (False, they are defined by indentation.)

  1. Fill in the blank: range(3, 8) produces the integers ______. (3, 4, 5, 6, 7.)

  1. True or False: A function without a return statement returns 0. (False, it returns None.)

  1. Fill in the blank: The first parameter of every method in a class is conventionally called ______. (self.)

  1. True or False: finally only runs if an exception was raised. (False, finally runs whether or not an exception occurred.)


Practice Q&A

Q: Write a for loop that prints each character of the string "apple" on a separate line.

A: for x in "apple": followed by print(x) (indented).

Q: What is the output of the following code?

i = 1
while i < 8:
    print(i)
    if i == 4:
        break
    i += 1

A: It prints 1, 2, 3, 4 on separate lines, then stops. The break fires when i reaches 4.

Q: Define a function add_numbers(x, y, z) that returns the sum of its three parameters.

A: def add_numbers(x, y, z): return x + y + z.

Q: What exception is raised by my_dict["nonexistent_key"]?

A: KeyError.

Q: What is the advantage of using with open(...) as f: over f = open(...)?

A: The with statement automatically closes the file when the block ends, even if an exception occurs. Without it, you must remember to call f.close() manually.


Connections to Other Topics

This connects to Data Structures because loops iterate over lists, dicts and sets, and functions commonly accept and return these containers.

This connects to Python Fundamentals because conditional statements rely on boolean expressions, comparison operators, and the truthiness rules covered there.

Classes connect to everything that follows in intermediate Python: inheritance, polymorphism, decorators and the standard library are all built on the class system.


Related Terms / Search Tags

Python if elif else, conditional statement, for loop, while loop, break continue, range(), enumerate(), zip(), function definition, def, return, parameters arguments, default values, keyword arguments, *args **kwargs, class, object, init, self, inheritance, subclass, method override, try except else finally, raise, TypeError ValueError KeyError IndexError NameError ZeroDivisionError SyntaxError ImportError, exception handling, file I/O, open read write close, with statement, context manager, module, import, from import, Python 3 control flow