NullSector NullSector

Up until now, if you wanted to do the same thing twice, you'd have to write the same code twice. Functions solve this - you write the code once, give it a name, and call it whenever you need it.

Functions are also how large programs are organized. Instead of thousands of lines in one file, you break code into logical, manageable pieces. Every serious program you'll ever write will be built from functions.

This chapter transforms you from someone who writes scripts to someone who writes structured, maintainable code.

๐Ÿญ The Factory Metaphor

Think of functions as machines in a factory:

  • Input (parameters): Raw materials you feed into the machine
  • Process (function body): What the machine does with the materials
  • Output (return value): The finished product that comes out

You design the machine once. Then you can use it to process any materials, as many times as you want. That's the power of functions.

๐Ÿ”„ Reusability

Write once, use everywhere. Need to greet users in 10 places? Write one greet function and call it 10 times.

๐Ÿ“ฆ Organization

Break complex problems into smaller, manageable pieces. Each function does one thing well.

๐Ÿ”ง Maintainability

Bug in your greeting? Fix it in one place (the function), and it's fixed everywhere.

๐Ÿงช Testability

Test individual functions in isolation. Much easier than testing a 500-line script.

DRY Principle

Don't Repeat Yourself. If you're copying code, you should probably make a function instead. Functions are the antidote to copy-paste programming.

What Are Functions?

A function is a named block of code that performs a specific task. You define it once and can call it as many times as you want. Functions are the building blocks of all structured programming.

๐Ÿ“‹ The Recipe Card Metaphor

Think of a function like a recipe card:

  • Function name = Recipe title ("Chocolate Cake")
  • Parameters = Ingredients needed (flour, sugar, eggs)
  • Function body = The cooking instructions
  • Return value = The finished dish

You write the recipe once. Then you can "call" it whenever you want cake - you don't rewrite the whole recipe every time!

You've Already Used Functions!

# ==================== BUILT-IN FUNCTIONS ==================== # These are all function CALLS: print("Hello") # print is a function - displays output len("Hello") # len is a function - returns length (5) int("42") # int is a function - converts to integer float("3.14") # float is a function - converts to float input("Name: ") # input is a function - gets user input type(42) # type is a function - returns the type max(1, 5, 3) # max is a function - returns maximum min(1, 5, 3) # min is a function - returns minimum # ==================== THE PATTERN ==================== # function_name(arguments) # โ†‘ โ†‘ # What to call What to give it # ==================== CHAINING FUNCTION CALLS ==================== # Functions return values that can be used immediately: length = len("Hello") # Store the result print(len("Hello")) # Use directly in another call total = sum([1, 2, 3, 4, 5]) # sum() returns a number text = str(42) + " is a number" # str() returns a string # ==================== NOW YOU'LL LEARN ==================== # These are BUILT-IN functions - Python provides them # Now you'll learn to create your OWN functions! # This is where programming gets really powerful

Anatomy of a Function

# ==================== THE PARTS OF A FUNCTION ==================== def greet(name): # โ† Function DEFINITION """Say hello to someone.""" # โ† Docstring (optional but recommended) message = f"Hello, {name}!" # โ† Function BODY return message # โ† RETURN statement result = greet("Alice") # โ† Function CALL print(result) # Hello, Alice! # ==================== BREAKING IT DOWN ==================== # 1. def keyword - "I'm defining a function" # 2. greet - The function's name (you choose this) # 3. (name) - Parameter(s) the function accepts # 4. : - Colon ends the function header # 5. Indented lines - The function body (what it does) # 6. return - What value to send back (optional) # ==================== CALLING THE FUNCTION ==================== # Defining doesn't RUN the code - it just saves it # Calling (with parentheses) actually runs it: greet("Bob") # Runs the function with "Bob" greet("Charlie") # Runs it again with "Charlie" # Each call is independent - name is "Bob" first, then "Charlie" # ==================== VISUALIZING THE FLOW ==================== # Program flow: # 1. Python reads the def and saves the function (doesn't run it) # 2. Continues past the function definition # 3. Encounters greet("Alice") - JUMPS into the function # 4. name becomes "Alice" # 5. Executes the body line by line # 6. Hits return, sends value back # 7. JUMPS back to where it was called # 8. Continues from there

๐Ÿ’ก Function Naming Best Practices

  • Use verbs: Functions DO things, so name them with action words (calculate_total, get_user, validate_input)
  • Be descriptive: calculate_average is better than calc or avg
  • Use snake_case: Python convention is lowercase with underscores
  • Avoid generic names: process, do_stuff, handle are too vague

Defining Your First Function

Creating a function is called "defining" it. You use the def keyword. Once defined, a function exists and waits to be called. The code inside doesn't run until you call the function.

Basic Function Definition

# ==================== BASIC SYNTAX ==================== def function_name(): """Optional docstring describing what the function does.""" # code goes here # indented with 4 spaces pass # placeholder if no code yet # ==================== SIMPLE EXAMPLE ==================== def say_hello(): print("Hello!") print("Welcome to Python!") print("Functions are awesome!") # At this point, nothing has been printed yet! # We've just DEFINED the function - saved it for later use # Now let's CALL it: say_hello() # Output: # Hello! # Welcome to Python! # Functions are awesome! # ==================== DEFINE VS CALL ==================== # DEFINITION (with def): # - Creates the function # - Stores the code for later # - Does NOT run the code # CALL (with parentheses): # - Actually runs the function # - Executes the code inside # - Can be done multiple times # ==================== FUNCTION WITHOUT ARGUMENTS ==================== def print_separator(): """Print a visual separator line.""" print("=" * 50) def print_welcome(): """Print a welcome banner.""" print_separator() print(" WELCOME TO MY PROGRAM") print_separator() print_welcome() # Output: # ================================================== # WELCOME TO MY PROGRAM # ==================================================

Define Once, Call Many Times

# ==================== REUSABILITY IN ACTION ==================== def greet(): print("Hello there!") print("Nice to meet you!") # Call it multiple times greet() # First call greet() # Second call greet() # Third call # Output: # Hello there! # Nice to meet you! # Hello there! # Nice to meet you! # Hello there! # Nice to meet you! # ==================== IN A LOOP ==================== def announce_round(number): print(f"\n=== ROUND {number} ===") for i in range(1, 4): announce_round(i) print("Fighting...") print("Round complete!") # ==================== FROM OTHER FUNCTIONS ==================== def step_one(): print("Step 1: Initialize") def step_two(): print("Step 2: Process") def step_three(): print("Step 3: Finalize") def run_all_steps(): """Run the complete procedure.""" print("Starting procedure...") step_one() step_two() step_three() print("Procedure complete!") run_all_steps() # Starting procedure... # Step 1: Initialize # Step 2: Process # Step 3: Finalize # Procedure complete!

Functions Must Be Defined Before Calling

# ==================== ORDER MATTERS ==================== # This WON'T work: # greet() # โŒ NameError: name 'greet' is not defined # def greet(): # print("Hi") # This WORKS: def greet(): # Define first print("Hi") greet() # Then call # ==================== BUT CALLS INSIDE FUNCTIONS ARE OK ==================== # This works because functions are defined before main() is called: def helper(): print("I'm helping!") def main(): print("Starting...") helper() # OK because helper is defined when main() runs print("Done!") main() # Python doesn't look inside main() until you call it # By then, helper() is already defined # ==================== COMMON PATTERN ==================== # Define all functions first, then call them at the bottom: def function_a(): function_b() # OK - function_b exists when this runs def function_b(): print("B!") # Main code at the bottom function_a()

โš ๏ธ Common Beginner Mistakes

  • Forgetting parentheses: greet refers to the function object, greet() calls it
  • Wrong indentation: All code inside the function must be indented equally
  • Calling before defining: The def statement must come before the call
  • Expecting automatic execution: Defining a function doesn't run it!

Parameters and Arguments

Functions become truly powerful when they accept input. Parameters are variables that receive values when the function is called. They let you customize what the function does each time.

๐Ÿ“ฌ The Mailbox Metaphor

Parameters are like mailboxes on a house:

  • Parameter: The mailbox (a slot to receive something)
  • Argument: The letter you put in the mailbox (the actual value)

When you call greet("Alice"), you're putting "Alice" (argument) into the name mailbox (parameter).

Single Parameter

# ==================== FUNCTION WITH A PARAMETER ==================== def greet(name): # 'name' is a PARAMETER (placeholder) print(f"Hello, {name}!") # Calling with an argument greet("Alice") # "Alice" is the ARGUMENT (actual value) greet("Bob") # "Bob" is the argument greet("Charlie") # "Charlie" is the argument # Output: # Hello, Alice! # Hello, Bob! # Hello, Charlie! # ==================== HOW IT WORKS ==================== # When you call greet("Alice"): # 1. Python sees greet("Alice") # 2. Jumps to the greet function # 3. Assigns name = "Alice" # 4. Runs the function body with name = "Alice" # 5. Returns to where it was called # Each call gets its own independent 'name' # ==================== PARAMETER VS ARGUMENT ==================== # People often use these interchangeably, but technically: # PARAMETER: Variable in the function definition (name) # ARGUMENT: Value passed when calling (Alice) def add(x, y): # x and y are PARAMETERS return x + y add(5, 3) # 5 and 3 are ARGUMENTS # ==================== DYNAMIC BEHAVIOR ==================== def double(number): return number * 2 print(double(5)) # 10 print(double(10)) # 20 print(double(100)) # 200 # Same function, different results based on input!

Multiple Parameters

# ==================== MULTIPLE PARAMETERS ==================== # Separate parameters with commas def introduce(name, age, city): print(f"Hi, I'm {name}!") print(f"I'm {age} years old.") print(f"I live in {city}.") print() # Empty line for spacing introduce("Alice", 25, "New York") introduce("Bob", 30, "London") introduce("Charlie", 22, "Tokyo") # ==================== ORDER MATTERS (POSITIONAL ARGUMENTS) ==================== # Arguments are matched to parameters by POSITION: # introduce(name, age, city) # โ†‘ โ†‘ โ†‘ # introduce("Alice", 25, "New York") # If you mix them up: introduce(25, "Alice", "New York") # โš ๏ธ Works but wrong! # Output: Hi, I'm 25! (not what we wanted) # ==================== PRACTICAL EXAMPLE ==================== def calculate_area(length, width): """Calculate the area of a rectangle.""" area = length * width return area room1 = calculate_area(10, 12) # 120 room2 = calculate_area(15, 8) # 120 room3 = calculate_area(20, 20) # 400 print(f"Room 1: {room1} sq ft") print(f"Room 2: {room2} sq ft") print(f"Room 3: {room3} sq ft") # ==================== MANY PARAMETERS ==================== def create_character(name, health, attack, defense, speed, level): """Create an RPG character.""" print(f"Creating {name}...") print(f" HP: {health}") print(f" ATK: {attack}") print(f" DEF: {defense}") print(f" SPD: {speed}") print(f" LVL: {level}") return {"name": name, "hp": health, "atk": attack, "def": defense, "spd": speed, "lvl": level} hero = create_character("Hero", 100, 25, 15, 10, 1)

Keyword Arguments

# ==================== NAMED ARGUMENTS ==================== # You can specify which parameter gets which value by name: def describe_pet(name, animal, color): print(f"{name} is a {color} {animal}") # Positional (order matters) describe_pet("Fluffy", "cat", "white") # Fluffy is a white cat # Keyword (order doesn't matter!) describe_pet(animal="dog", color="brown", name="Rex") # Rex is a brown dog describe_pet(color="orange", name="Nemo", animal="fish") # Nemo is an orange fish # ==================== MIXING POSITIONAL AND KEYWORD ==================== # Positional arguments must come FIRST describe_pet("Tweety", animal="bird", color="yellow") # โœ“ OK # This is wrong: # describe_pet(name="Tweety", "bird", "yellow") # โŒ SyntaxError # ==================== WHY USE KEYWORD ARGUMENTS? ==================== # 1. Clarity - you know what each value means: create_user("alice", 25, "NYC", True, False, "admin") # What are those bools? create_user("alice", age=25, city="NYC", active=True, verified=False, role="admin") # Much clearer! # 2. Order independence - useful for many parameters # 3. Self-documenting code - reads like prose # ==================== PRACTICAL EXAMPLE ==================== def format_price(amount, currency="$", decimals=2, show_symbol=True): """Format a price for display.""" if show_symbol: return f"{currency}{amount:.{decimals}f}" else: return f"{amount:.{decimals}f}" print(format_price(19.99)) # $19.99 print(format_price(19.99, currency="โ‚ฌ")) # โ‚ฌ19.99 print(format_price(19.99, decimals=0)) # $20 print(format_price(19.99, show_symbol=False)) # 19.99 print(format_price(19.99, "ยฃ", 2, True)) # ยฃ19.99

*args and **kwargs (Variable Arguments)

# ==================== *args - VARIABLE POSITIONAL ARGUMENTS ==================== # *args collects extra positional arguments into a tuple def add_all(*numbers): """Add any number of numbers together.""" total = 0 for num in numbers: total += num return total print(add_all(1, 2)) # 3 print(add_all(1, 2, 3, 4, 5)) # 15 print(add_all(10)) # 10 print(add_all()) # 0 # numbers is a tuple containing all the arguments # ==================== **kwargs - VARIABLE KEYWORD ARGUMENTS ==================== # **kwargs collects extra keyword arguments into a dictionary def print_info(**details): """Print any information provided.""" for key, value in details.items(): print(f"{key}: {value}") print_info(name="Alice", age=25) # name: Alice # age: 25 print_info(title="Manager", department="Sales", years=5) # title: Manager # department: Sales # years: 5 # ==================== COMBINING THEM ==================== def super_function(required, *args, default="value", **kwargs): print(f"Required: {required}") print(f"Extra args: {args}") print(f"Default: {default}") print(f"Extra kwargs: {kwargs}") super_function("must have", 1, 2, 3, default="custom", extra="stuff", more="things") # Required: must have # Extra args: (1, 2, 3) # Default: custom # Extra kwargs: {'extra': 'stuff', 'more': 'things'} # ==================== ORDER OF PARAMETERS ==================== # The order must be: # 1. Regular positional parameters # 2. *args # 3. Keyword-only parameters (including defaults) # 4. **kwargs def ordered(a, b, *args, c, d="default", **kwargs): pass # Correct order!

๐Ÿ’ก When to Use Each Type

  • Required positional: Values the function always needs
  • Default parameters: Optional values with sensible defaults
  • *args: Unknown number of similar items (like numbers to sum)
  • **kwargs: Unknown configuration options or metadata

Return Values

Functions can send back a result using the return statement. This is how functions give you useful output that you can store, manipulate, or pass to other functions. Return values are what make functions truly powerful.

๐Ÿญ The Vending Machine

A function with return is like a vending machine:

  • Arguments: Money and button press (what you put in)
  • Function body: The machine's internal process
  • Return value: The snack that comes out (what you get back)

You don't just want the machine to display "Dispensed!" - you want the actual snack. That's what return does.

Basic Return

# ==================== FUNCTION THAT RETURNS A VALUE ==================== def add(a, b): result = a + b return result # Send the result back to the caller # Using the returned value sum1 = add(5, 3) # sum1 = 8 sum2 = add(10, 20) # sum2 = 30 print(sum1) # 8 print(sum2) # 30 # ==================== USING RETURN VALUES DIRECTLY ==================== # You can use the return value immediately: print(add(100, 200)) # 300 # In expressions: total = add(5, 3) + add(10, 20) # 8 + 30 = 38 # As arguments to other functions: double_sum = add(add(1, 2), add(3, 4)) # add(3, 7) = 10 # In conditions: if add(5, 5) == 10: print("Math works!") # ==================== SIMPLIFIED RETURN ==================== # You don't need a separate variable: def add(a, b): return a + b # Calculate and return in one line def multiply(a, b): return a * b def power(base, exp): return base ** exp # ==================== FUNCTIONS THAT DON'T RETURN ==================== # If a function doesn't have a return statement, it returns None def greet(name): print(f"Hello, {name}!") # No return statement result = greet("Alice") # Prints "Hello, Alice!" print(result) # None # This is fine for functions that just DO something # But use return for functions that CALCULATE something

โš ๏ธ print() vs return - Critical Difference!

print() displays text on screen but returns None.

return sends a value back that you can store and use.

# WRONG - uses print def add_wrong(a, b): print(a + b) # Displays result, returns None result = add_wrong(5, 3) # Prints "8" print(result * 2) # ERROR! None * 2 # RIGHT - uses return def add_right(a, b): return a + b # Returns the value result = add_right(5, 3) # result = 8 print(result * 2) # 16

Return Ends the Function

# ==================== RETURN EXITS IMMEDIATELY ==================== def test(): print("Before return") return "Done" print("After return") # โš ๏ธ This NEVER executes! result = test() # Output: Before return # result = "Done" # The code after return is "dead code" - unreachable # ==================== EARLY RETURNS FOR VALIDATION ==================== def divide(a, b): # Check for error condition first if b == 0: return "Error: Cannot divide by zero" # Only reach here if b != 0 return a / b print(divide(10, 2)) # 5.0 print(divide(10, 0)) # Error: Cannot divide by zero # ==================== MULTIPLE EXIT POINTS ==================== def grade(score): if score >= 90: return "A" if score >= 80: return "B" if score >= 70: return "C" if score >= 60: return "D" return "F" # Each return exits the function immediately # No need for elif when using return! print(grade(95)) # A print(grade(82)) # B print(grade(50)) # F # ==================== GUARD CLAUSES PATTERN ==================== def process_user(user): # Handle error cases first (guard clauses) if user is None: return "Error: No user provided" if not user.get("active"): return "Error: User is inactive" if user.get("age", 0) < 18: return "Error: User is underage" # Main logic only runs if all checks pass return f"Processing {user['name']}..." # Clean and readable - errors handled at the top

Returning Multiple Values

# ==================== RETURN MULTIPLE VALUES ==================== # Python can return multiple values as a tuple! def get_stats(numbers): total = sum(numbers) count = len(numbers) average = total / count minimum = min(numbers) maximum = max(numbers) return total, count, average, minimum, maximum # Unpack the returned values data = [10, 20, 30, 40, 50] total, count, avg, low, high = get_stats(data) print(f"Sum: {total}") # 150 print(f"Count: {count}") # 5 print(f"Average: {avg}") # 30.0 print(f"Range: {low}-{high}") # 10-50 # ==================== HOW IT WORKS ==================== # When you write: return a, b, c # Python creates a tuple: (a, b, c) # When you write: x, y, z = func() # Python unpacks the tuple result = get_stats(data) print(result) # (150, 5, 30.0, 10, 50) - it's a tuple print(type(result)) # <class 'tuple'> # You can also access by index: print(result[0]) # 150 (total) print(result[2]) # 30.0 (average) # ==================== PARTIAL UNPACKING ==================== # If you only need some values: total, _, avg, _, _ = get_stats(data) # _ ignores values # Or use indexing: avg = get_stats(data)[2] # ==================== RETURNING DICTIONARIES ==================== # For many values, a dictionary is often clearer: def analyze_text(text): words = text.split() return { "char_count": len(text), "word_count": len(words), "avg_word_length": len(text.replace(" ", "")) / len(words), "longest_word": max(words, key=len) } stats = analyze_text("The quick brown fox jumps over the lazy dog") print(f"Words: {stats['word_count']}") print(f"Longest: {stats['longest_word']}")

Returning None

# ==================== EXPLICIT NONE RETURN ==================== # Sometimes you explicitly return None to indicate "no result" def find_user(user_id, users): for user in users: if user["id"] == user_id: return user return None # Not found users = [ {"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"} ] result = find_user(1, users) if result: print(f"Found: {result['name']}") else: print("User not found") result = find_user(99, users) # Returns None if result is None: print("User 99 not found") # ==================== IMPLICIT NONE ==================== # Functions without return (or with bare return) return None def say_hello(): print("Hello!") # No return statement โ†’ returns None def do_nothing(): return # Bare return โ†’ returns None print(say_hello()) # Prints "Hello!" then None print(do_nothing()) # None

๐Ÿ’ก Return Value Best Practices

  • Be consistent: Always return the same type (or None for errors)
  • Document returns: Use docstrings to explain what's returned
  • Avoid side effects: Functions that return should generally not print
  • Use early returns: Guard clauses make code cleaner
  • Consider dictionaries: Better than tuples when returning many values

Variable Scope

Variables created inside a function only exist inside that function. This is called "scope" and it's crucial to understand. Scope determines where variables can be accessed and how long they live.

๐Ÿ  The Room Metaphor

Think of each function as a room in a house:

  • Local variables = Items in your room (only you can use them)
  • Global variables = Items in the shared living room (everyone can see them)
  • When the function ends = You leave the room, and everything in it is cleaned up

Your bedroom's stuff doesn't exist to someone in another room. Similarly, local variables don't exist outside their function.

Local Scope

# ==================== LOCAL VARIABLES ==================== # Variables created INSIDE a function are LOCAL # They only exist while the function is running def my_function(): x = 10 # x is LOCAL to my_function print(f"Inside function: x = {x}") my_function() # Works: Inside function: x = 10 # print(x) # โŒ NameError: name 'x' is not defined # x doesn't exist outside the function! # ==================== EACH CALL IS FRESH ==================== def counter(): count = 0 # Created fresh each call count += 1 return count print(counter()) # 1 print(counter()) # 1 (not 2!) print(counter()) # 1 (still 1!) # count is destroyed when the function ends # Created fresh (at 0) on the next call # ==================== PARAMETERS ARE LOCAL TOO ==================== def greet(name): # 'name' is a local variable (from parameter) message = f"Hello, {name}!" # 'message' is also local return message greet("Alice") # print(name) # โŒ NameError # print(message) # โŒ NameError # ==================== SAME NAME, DIFFERENT VARIABLES ==================== x = "global" def my_function(): x = "local" # This is a DIFFERENT x! print(f"Inside: {x}") my_function() # Inside: local print(f"Outside: {x}") # Outside: global # The function created a new local x # It didn't change the global x

Global Scope

# ==================== GLOBAL VARIABLES ==================== # Variables created OUTSIDE any function are GLOBAL # They can be READ from anywhere message = "Hello, World!" # Global variable def greet(): print(message) # Can READ global variables greet() # Hello, World! # ==================== FUNCTIONS CAN'T MODIFY GLOBALS (BY DEFAULT) ==================== counter = 0 def increment(): counter = counter + 1 # โŒ UnboundLocalError! # Why? Python sees "counter = ..." and thinks you're creating # a LOCAL variable. But you're trying to read it before creating it. # ==================== THE GLOBAL KEYWORD ==================== counter = 0 def increment(): global counter # Tell Python: "I want the global counter" counter += 1 increment() increment() increment() print(counter) # 3 # ==================== READ VS MODIFY ==================== value = 100 def can_read(): print(value) # โœ“ Reading global is fine def cannot_modify(): value += 1 # โŒ Error without 'global' def can_modify(): global value value += 1 # โœ“ With 'global', can modify can_read() # 100 can_modify() print(value) # 101

โš ๏ธ Why Avoid Global Variables?

  • Hard to track: Any function could change them
  • Hidden dependencies: Functions secretly depend on external state
  • Testing nightmare: Need to set up global state before testing
  • Name conflicts: Easy to accidentally reuse names

Better approach: Pass values as parameters and return results!

The Right Way: Parameters and Returns

# ==================== BAD: USING GLOBALS ==================== total = 0 def add_to_total_bad(amount): global total total += amount add_to_total_bad(10) add_to_total_bad(20) print(total) # 30 # Problems: # - Hard to test add_to_total_bad in isolation # - Hidden state makes debugging difficult # - Another function could accidentally reset total # ==================== GOOD: USING PARAMETERS/RETURNS ==================== def add_to_total_good(current_total, amount): return current_total + amount total = 0 total = add_to_total_good(total, 10) total = add_to_total_good(total, 20) print(total) # 30 # Benefits: # - Function is pure - output depends only on input # - Easy to test: add_to_total_good(0, 10) should return 10 # - No hidden state, no surprises # ==================== PRACTICAL EXAMPLE ==================== # BAD: Game using globals lives = 3 score = 0 def take_damage(): global lives lives -= 1 def add_score(points): global score score += points # GOOD: Game using objects/classes (Chapter 6) # or using dictionaries: def take_damage(game_state): return {**game_state, "lives": game_state["lives"] - 1} def add_score(game_state, points): return {**game_state, "score": game_state["score"] + points} state = {"lives": 3, "score": 0} state = take_damage(state) state = add_score(state, 100) print(state) # {'lives': 2, 'score': 100}

Scope Hierarchy (LEGB Rule)

# ==================== PYTHON'S SCOPE LOOKUP ORDER ==================== # When Python sees a variable name, it searches in this order: # L - Local (inside current function) # E - Enclosing (inside outer functions, for nested functions) # G - Global (module level) # B - Built-in (Python's built-in names like print, len) # ==================== EXAMPLE ==================== x = "global" # Global scope def outer(): x = "enclosing" # Enclosing scope (for inner) def inner(): x = "local" # Local scope print(x) # Prints: local inner() print(x) # Prints: enclosing outer() print(x) # Prints: global # ==================== NONLOCAL KEYWORD ==================== # To modify an enclosing (but not global) variable: def outer(): count = 0 def inner(): nonlocal count # Modify the outer function's count count += 1 return count return inner counter = outer() print(counter()) # 1 print(counter()) # 2 print(counter()) # 3 # This pattern is called a "closure" - inner() "closes over" count

๐Ÿ’ก Scope Best Practices

  • Minimize globals: Use them only for true constants
  • Pass data explicitly: Use parameters instead of global reads
  • Return results: Instead of modifying global state
  • Use UPPERCASE: For constants that should be global (e.g., MAX_SIZE = 100)
  • Keep functions pure: Same input โ†’ same output, no side effects

Default Parameter Values

You can give parameters default values. If no argument is provided, the default is used. This makes functions more flexible - you can call them with fewer arguments while still having sensible behavior.

Basic Default Parameters

# ==================== SINGLE DEFAULT ==================== def greet(name, greeting="Hello"): print(f"{greeting}, {name}!") greet("Alice") # Hello, Alice! (uses default) greet("Bob", "Hi") # Hi, Bob! (overrides default) greet("Charlie", "Hey") # Hey, Charlie! # ==================== HOW IT WORKS ==================== # def greet(name, greeting="Hello") # โ†‘ โ†‘ # | โ””โ”€โ”€ Has default: optional when calling # โ””โ”€โ”€ No default: required when calling greet("Alice") # โœ“ greeting defaults to "Hello" # greet() # โŒ TypeError: missing required 'name' greet("Alice", "Howdy") # โœ“ Override the default # ==================== MULTIPLE DEFAULTS ==================== def create_user(name, age=0, city="Unknown", active=True): return { "name": name, "age": age, "city": city, "active": active } # All these work: user1 = create_user("Alice") # {'name': 'Alice', 'age': 0, 'city': 'Unknown', 'active': True} user2 = create_user("Bob", 25) # {'name': 'Bob', 'age': 25, 'city': 'Unknown', 'active': True} user3 = create_user("Charlie", 30, "NYC") # {'name': 'Charlie', 'age': 30, 'city': 'NYC', 'active': True} user4 = create_user("Diana", 22, "London", False) # {'name': 'Diana', 'age': 22, 'city': 'London', 'active': False} # ==================== SKIPPING DEFAULTS WITH KEYWORDS ==================== # What if you want to set 'active' but not 'age' or 'city'? # Use keyword arguments! user5 = create_user("Eve", active=False) # {'name': 'Eve', 'age': 0, 'city': 'Unknown', 'active': False} user6 = create_user("Frank", city="Paris") # {'name': 'Frank', 'age': 0, 'city': 'Paris', 'active': True}

Parameter Ordering Rules

# ==================== DEFAULTS MUST COME LAST ==================== # Parameters with defaults MUST come after parameters without: def good(required, optional="default"): pass # โœ“ OK # def bad(optional="default", required): # pass # โŒ SyntaxError! # Why? Imagine calling bad("hello") # Is "hello" for 'optional' or 'required'? Ambiguous! # ==================== THE CORRECT ORDER ==================== # 1. Required positional parameters # 2. Optional parameters with defaults # 3. *args (if needed) # 4. Keyword-only parameters # 5. **kwargs (if needed) def complete_function( required1, # Required positional required2, # Required positional optional1="default1", # Optional with default optional2="default2", # Optional with default *args, # Extra positional args keyword_only="kwdefault", # After *args: keyword-only **kwargs # Extra keyword args ): pass # ==================== PRACTICAL EXAMPLE ==================== def format_name(first, last, middle="", title="", suffix=""): """Format a person's full name.""" parts = [] if title: parts.append(title) parts.append(first) if middle: parts.append(middle) parts.append(last) if suffix: parts.append(suffix) return " ".join(parts) print(format_name("John", "Doe")) # John Doe print(format_name("John", "Doe", middle="Q")) # John Q Doe print(format_name("John", "Doe", title="Dr.", suffix="Jr.")) # Dr. John Doe Jr.

โš ๏ธ Mutable Default Arguments: A Python Gotcha!

Never use mutable objects (lists, dicts) as default values!

# BAD - The list is created ONCE and reused! def add_item_bad(item, items=[]): items.append(item) return items print(add_item_bad("a")) # ['a'] print(add_item_bad("b")) # ['a', 'b'] โ† Surprise! print(add_item_bad("c")) # ['a', 'b', 'c'] โ† Yikes! # GOOD - Use None and create inside def add_item_good(item, items=None): if items is None: items = [] items.append(item) return items print(add_item_good("a")) # ['a'] print(add_item_good("b")) # ['b'] โœ“ Fresh list

Common Use Cases

# ==================== CONFIGURATION OPTIONS ==================== def connect_db(host, port=5432, user="admin", password="", ssl=True): """Connect to a database with sensible defaults.""" print(f"Connecting to {user}@{host}:{port} (SSL: {ssl})") # ... actual connection code connect_db("localhost") # Connecting to admin@localhost:5432 (SSL: True) connect_db("db.example.com", user="myapp", password="secret") # Connecting to myapp@db.example.com:5432 (SSL: True) # ==================== OPTIONAL FEATURES ==================== def search(query, case_sensitive=False, max_results=10, include_meta=False): """Search with optional settings.""" print(f"Searching: {query}") print(f" Case sensitive: {case_sensitive}") print(f" Max results: {max_results}") print(f" Include metadata: {include_meta}") search("python") # Simple call search("Python", case_sensitive=True) # Exact case search("python", max_results=100) # More results # ==================== POLYMORPHIC BEHAVIOR ==================== def greet(name, times=1, excited=False): """Greet someone, optionally multiple times with excitement.""" greeting = f"Hello, {name}!" if excited: greeting = greeting.upper() + "!!" for _ in range(times): print(greeting) greet("Alice") # Hello, Alice! greet("Bob", times=3) # Hello, Bob! (3 times) greet("Charlie", excited=True) # HELLO, CHARLIE!!! greet("Diana", times=2, excited=True) # HELLO, DIANA!!! (2 times)

๐Ÿ’ก Default Parameter Best Practices

  • Use for common cases: Most calls should work with defaults
  • Never use mutable defaults: Use None and create inside function
  • Document defaults: Include in docstrings
  • Keep it simple: Too many defaults makes function hard to understand
  • Use keyword arguments: When skipping some defaults

Lambda Functions

Lambda functions are small, anonymous functions defined in one line. They're useful for simple operations that you need to pass around, especially with functions like sort(), filter(), and map().

๐Ÿ“ The Sticky Note vs Letter

Regular functions are like formal letters - proper heading, body, signature.

Lambda functions are like sticky notes - quick, disposable, for simple messages.

Use sticky notes when a full letter is overkill!

Lambda Basics

# ==================== LAMBDA SYNTAX ==================== # Regular function: def square(x): return x ** 2 # Same thing as lambda: square = lambda x: x ** 2 print(square(5)) # 25 # ==================== THE STRUCTURE ==================== # lambda arguments: expression # โ†‘ โ†‘ โ†‘ # | | โ””โ”€โ”€ What to return (single expression) # | โ””โ”€โ”€ Input parameters # โ””โ”€โ”€ The lambda keyword # ==================== EXAMPLES ==================== # One parameter: double = lambda x: x * 2 print(double(5)) # 10 # Two parameters: add = lambda a, b: a + b print(add(3, 4)) # 7 # No parameters: get_pi = lambda: 3.14159 print(get_pi()) # 3.14159 # Conditional expression: absolute = lambda x: x if x >= 0 else -x print(absolute(-5)) # 5 print(absolute(3)) # 3 # ==================== IMPORTANT LIMITATIONS ==================== # Lambdas can only contain a SINGLE expression # No statements (no if:, no for:, no =) # This WON'T work: # wrong = lambda x: if x > 0: return x # โŒ SyntaxError # Use a regular function for complex logic: def complex_logic(x): if x > 0: return x else: return 0

Lambda with Built-in Functions

# ==================== SORTING WITH LAMBDA ==================== students = [ {"name": "Alice", "grade": 85}, {"name": "Bob", "grade": 92}, {"name": "Charlie", "grade": 78}, {"name": "Diana", "grade": 95} ] # Sort by grade (ascending) students.sort(key=lambda s: s["grade"]) print([s["name"] for s in students]) # ['Charlie', 'Alice', 'Bob', 'Diana'] # Sort by grade (descending) students.sort(key=lambda s: s["grade"], reverse=True) print([s["name"] for s in students]) # ['Diana', 'Bob', 'Alice', 'Charlie'] # Sort by name students.sort(key=lambda s: s["name"]) print([s["name"] for s in students]) # ['Alice', 'Bob', 'Charlie', 'Diana'] # ==================== FILTERING WITH LAMBDA ==================== numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # Keep only even numbers evens = list(filter(lambda x: x % 2 == 0, numbers)) print(evens) # [2, 4, 6, 8, 10] # Keep numbers greater than 5 big = list(filter(lambda x: x > 5, numbers)) print(big) # [6, 7, 8, 9, 10] # ==================== MAPPING WITH LAMBDA ==================== # Square all numbers squared = list(map(lambda x: x ** 2, numbers)) print(squared) # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] # Convert to strings strings = list(map(lambda x: str(x), numbers)) print(strings) # ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'] # ==================== REDUCE WITH LAMBDA ==================== from functools import reduce # Sum all numbers (fold left) total = reduce(lambda acc, x: acc + x, numbers) print(total) # 55 # Product of all numbers product = reduce(lambda acc, x: acc * x, numbers) print(product) # 3628800 (10!)

Practical Lambda Examples

# ==================== SORTING COMPLEX DATA ==================== files = ["report.pdf", "photo.jpg", "video.mp4", "doc.txt"] # Sort by file extension files_sorted = sorted(files, key=lambda f: f.split(".")[-1]) print(files_sorted) # ['photo.jpg', 'video.mp4', 'report.pdf', 'doc.txt'] # ==================== QUICK TRANSFORMATIONS ==================== names = ["ALICE", "BOB", "CHARLIE"] # Capitalize properly proper = list(map(lambda n: n.capitalize(), names)) print(proper) # ['Alice', 'Bob', 'Charlie'] # ==================== INLINE CALLBACKS ==================== # Using lambda as a quick callback def process_data(data, transformer): return [transformer(item) for item in data] numbers = [1, 2, 3, 4, 5] result = process_data(numbers, lambda x: x * 10) print(result) # [10, 20, 30, 40, 50] # ==================== DICTIONARY SORTING ==================== scores = {"Alice": 85, "Bob": 92, "Charlie": 78} # Sort by value sorted_by_score = sorted(scores.items(), key=lambda item: item[1]) print(sorted_by_score) # [('Charlie', 78), ('Alice', 85), ('Bob', 92)] # Sort by value descending sorted_desc = sorted(scores.items(), key=lambda item: item[1], reverse=True) print(sorted_desc) # [('Bob', 92), ('Alice', 85), ('Charlie', 78)]

๐Ÿ’ก Lambda vs Regular Functions

Use Lambda Use Regular Function
Simple, single expression Multiple lines or statements
Used once, inline Reused multiple times
As argument to sort/map/filter Needs documentation
Quick and obvious logic Complex logic needing a name

Essential Built-in Functions

Python comes with many useful functions built in - no imports needed! These are your everyday tools that you'll use constantly. Understanding them deeply will make your code shorter, cleaner, and more Pythonic.

๐Ÿ› ๏ธ The Home Toolkit

Built-in functions are like the basic tools everyone has at home - hammer, screwdriver, pliers.

You don't buy them separately or look for them. They're just there, ready to use.

Master these first before learning specialized libraries!

Type Conversion Functions

These functions convert data from one type to another:

# ==================== STRING TO NUMBER ==================== # int() - Convert to integer int("42") # 42 int(" 42 ") # 42 (strips whitespace) int(3.7) # 3 (truncates, doesn't round!) int(3.2) # 3 int("1010", 2) # 10 (binary to decimal) int("ff", 16) # 255 (hex to decimal) int("77", 8) # 63 (octal to decimal) # float() - Convert to floating point float("3.14") # 3.14 float("3") # 3.0 float("inf") # inf (infinity) float("-inf") # -inf float("1e10") # 10000000000.0 (scientific notation) # ==================== TO STRING ==================== # str() - Convert to string str(100) # "100" str(3.14) # "3.14" str(True) # "True" str([1, 2, 3]) # "[1, 2, 3]" str({"a": 1}) # "{'a': 1}" # repr() - String representation (for debugging) repr("hello") # "'hello'" (includes quotes) repr(42) # "42" # ==================== TO BOOLEAN ==================== # bool() - Convert to boolean bool(1) # True bool(0) # False bool(-1) # True (any non-zero = True) bool("") # False (empty string) bool("hello") # True (non-empty string) bool([]) # False (empty list) bool([1, 2]) # True (non-empty list) bool(None) # False # "Falsy" values in Python: # 0, 0.0, "", [], {}, (), None, False # ==================== TO COLLECTIONS ==================== # list() - Convert to list list("abc") # ['a', 'b', 'c'] list((1, 2, 3)) # [1, 2, 3] (tuple to list) list({1, 2, 3}) # [1, 2, 3] (set to list) list(range(5)) # [0, 1, 2, 3, 4] list({"a": 1, "b": 2}) # ['a', 'b'] (keys only) # tuple() - Convert to tuple tuple([1, 2, 3]) # (1, 2, 3) tuple("abc") # ('a', 'b', 'c') # set() - Convert to set (removes duplicates!) set([1, 2, 2, 3]) # {1, 2, 3} set("hello") # {'h', 'e', 'l', 'o'} # dict() - Create dictionary dict([("a", 1), ("b", 2)]) # {'a': 1, 'b': 2} dict(a=1, b=2) # {'a': 1, 'b': 2}

Math Functions

# ==================== BASIC MATH ==================== # abs() - Absolute value abs(-5) # 5 abs(5) # 5 abs(-3.14) # 3.14 abs(3 + 4j) # 5.0 (complex number magnitude) # pow() - Power (exponentiation) pow(2, 3) # 8 (2^3) pow(10, 2) # 100 pow(2, -1) # 0.5 (2^-1 = 1/2) pow(2, 10, 100) # 24 (modular: 2^10 % 100) # round() - Rounding round(3.7) # 4 round(3.2) # 3 round(3.5) # 4 (banker's rounding) round(4.5) # 4 (rounds to even!) round(3.14159, 2) # 3.14 round(3.14159, 4) # 3.1416 round(1234, -2) # 1200 (round to hundreds) # divmod() - Division and modulus at once divmod(17, 5) # (3, 2) - quotient and remainder q, r = divmod(17, 5) print(f"17 รท 5 = {q} remainder {r}") # 17 รท 5 = 3 remainder 2 # ==================== AGGREGATION ==================== numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # max() - Maximum value max(1, 5, 3) # 5 max(numbers) # 10 max("apple", "banana", "cherry") # 'cherry' (alphabetically) max(numbers, key=lambda x: x % 3) # 8 (max remainder when /3) # min() - Minimum value min(1, 5, 3) # 1 min(numbers) # 1 min("apple", "banana") # 'apple' # sum() - Add all elements sum(numbers) # 55 sum([1, 2, 3], 10) # 16 (start at 10, add 1+2+3) sum([[1,2], [3,4]], []) # [1, 2, 3, 4] (flatten lists)

Sequence Functions

# ==================== LENGTH & MEMBERSHIP ==================== # len() - Get length len("hello") # 5 len([1, 2, 3]) # 3 len({"a": 1}) # 1 (number of keys) len(range(100)) # 100 # ==================== SORTING ==================== # sorted() - Return sorted list sorted([3, 1, 2]) # [1, 2, 3] sorted([3, 1, 2], reverse=True) # [3, 2, 1] sorted("hello") # ['e', 'h', 'l', 'l', 'o'] # Sort by key function words = ["banana", "pie", "apple"] sorted(words) # ['apple', 'banana', 'pie'] sorted(words, key=len) # ['pie', 'apple', 'banana'] sorted(words, key=len, reverse=True) # ['banana', 'apple', 'pie'] # reversed() - Reverse iterator list(reversed([1, 2, 3])) # [3, 2, 1] list(reversed("hello")) # ['o', 'l', 'l', 'e', 'h'] # ==================== RANGE ==================== # range() - Sequence of numbers list(range(5)) # [0, 1, 2, 3, 4] list(range(2, 7)) # [2, 3, 4, 5, 6] list(range(0, 10, 2)) # [0, 2, 4, 6, 8] list(range(10, 0, -1)) # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] list(range(10, 0, -2)) # [10, 8, 6, 4, 2] # ==================== ENUMERATE & ZIP ==================== # enumerate() - Add index to iteration fruits = ['apple', 'banana', 'cherry'] for i, fruit in enumerate(fruits): print(f"{i}: {fruit}") # 0: apple # 1: banana # 2: cherry # Start from different number for i, fruit in enumerate(fruits, start=1): print(f"{i}. {fruit}") # 1. apple # 2. banana # 3. cherry # zip() - Combine iterables names = ['Alice', 'Bob', 'Charlie'] scores = [85, 92, 78] grades = ['B', 'A', 'C'] for name, score in zip(names, scores): print(f"{name}: {score}") # Alice: 85 # Bob: 92 # Charlie: 78 # Zip multiple for name, score, grade in zip(names, scores, grades): print(f"{name}: {score} ({grade})") # Create dictionary from two lists student_scores = dict(zip(names, scores)) # {'Alice': 85, 'Bob': 92, 'Charlie': 78}

Logic Functions

# ==================== ALL & ANY ==================== numbers = [2, 4, 6, 8, 10] # all() - True if ALL elements are truthy all([True, True, True]) # True all([True, False, True]) # False all([1, 2, 3]) # True (all non-zero) all([1, 0, 3]) # False (0 is falsy) all([]) # True (vacuously true) # Check if all numbers are even all(n % 2 == 0 for n in numbers) # True # Check if all positive all(n > 0 for n in [1, 2, -3]) # False # any() - True if ANY element is truthy any([False, False, True]) # True any([False, False, False]) # False any([0, 0, 1]) # True any([]) # False # Check if any number is negative any(n < 0 for n in [-1, 2, 3]) # True any(n < 0 for n in [1, 2, 3]) # False # ==================== PRACTICAL EXAMPLE ==================== def validate_password(password): checks = [ len(password) >= 8, # At least 8 chars any(c.isupper() for c in password), # Has uppercase any(c.islower() for c in password), # Has lowercase any(c.isdigit() for c in password), # Has digit ] return all(checks) print(validate_password("Secret123")) # True print(validate_password("secret")) # False

Object Introspection

# ==================== TYPE CHECKING ==================== # type() - Get the type type(42) # type("hello") # type([1, 2, 3]) # type(print) # # isinstance() - Check if instance of type isinstance(42, int) # True isinstance("hi", str) # True isinstance([1,2], list) # True isinstance(42, (int, float)) # True (either type) # ==================== ATTRIBUTES ==================== # dir() - List all attributes/methods dir([]) # Shows all list methods dir(str) # Shows all string methods # hasattr(), getattr(), setattr() class Person: name = "Alice" hasattr(Person, "name") # True hasattr(Person, "age") # False getattr(Person, "name") # "Alice" getattr(Person, "age", 25) # 25 (default) # ==================== HELP ==================== # help() - Get documentation help(print) # Shows print function docs help(str) # Shows string class docs help([].append) # Shows list.append docs # id() - Get object's unique identifier x = [1, 2, 3] y = x z = [1, 2, 3] id(x) == id(y) # True (same object) id(x) == id(z) # False (different object) # callable() - Check if object can be called callable(print) # True callable(42) # False callable(lambda x: x) # True

Input/Output

# ==================== PRINTING ==================== # print() - Output to console print("Hello") # Hello print("Hello", "World") # Hello World print("a", "b", "c", sep="-") # a-b-c print("Loading", end="") # No newline print(".", end="") print(".", end="") # Loading... print("Done!") # ==================== USER INPUT ==================== # input() - Get user input name = input("Enter your name: ") print(f"Hello, {name}!") # Input is always a string! age_str = input("Enter age: ") age = int(age_str) # Convert to integer # One-liner age = int(input("Enter age: ")) # ==================== FILE OPERATIONS ==================== # open() - Open files # Read entire file with open("file.txt", "r") as f: content = f.read() # Read lines with open("file.txt", "r") as f: lines = f.readlines() # Write to file with open("output.txt", "w") as f: f.write("Hello, World!") # Append to file with open("log.txt", "a") as f: f.write("New log entry\n")

๐Ÿ’ก Most Used Built-in Functions

print()

Output to console

len()

Get length of sequence

range()

Generate number sequences

type()

Check variable type

int(), str(), float()

Type conversion

input()

Get user input

sorted()

Sort any sequence

enumerate()

Index + value iteration

Complete Example: Building a Calculator

# calculator.py - A complete calculator using functions # This demonstrates all the function concepts we've learned def add(a, b): """Add two numbers.""" return a + b def subtract(a, b): """Subtract b from a.""" return a - b def multiply(a, b): """Multiply two numbers.""" return a * b def divide(a, b): """ Divide a by b. Args: a: The dividend b: The divisor Returns: The quotient, or error message if b is zero """ if b == 0: return "Error: Division by zero!" return a / b def power(a, b): """Raise a to the power of b.""" return a ** b def get_number(prompt): """ Get a number from the user with validation. Keeps asking until valid input is received. """ while True: try: return float(input(prompt)) except ValueError: print("Invalid input! Please enter a number.") def get_numbers(): """Get two numbers from user.""" a = get_number("First number: ") b = get_number("Second number: ") return a, b def show_menu(): """Display the calculator menu.""" print("\n" + "=" * 30) print(" CALCULATOR") print("=" * 30) print("1. Add") print("2. Subtract") print("3. Multiply") print("4. Divide") print("5. Power") print("6. Quit") print("=" * 30) def calculate(choice, a, b): """ Perform calculation based on user choice. Uses a dictionary to map choices to functions. """ operations = { "1": ("Addition", add), "2": ("Subtraction", subtract), "3": ("Multiplication", multiply), "4": ("Division", divide), "5": ("Power", power) } if choice in operations: name, func = operations[choice] result = func(a, b) return f"{name}: {result}" return "Invalid operation" def main(): """ Main program loop. This is the entry point of the calculator. """ print("Welcome to the Python Calculator!") while True: show_menu() choice = input("Choose an option (1-6): ") if choice == "6": print("Thanks for using the calculator. Goodbye!") break if choice not in ["1", "2", "3", "4", "5"]: print("Invalid choice! Please select 1-6.") continue a, b = get_numbers() result = calculate(choice, a, b) print(f"\n>> {result}") # Only run if this file is executed directly if __name__ == "__main__": main()

โš ๏ธ Built-in Functions Quick Reference

Python has 68 built-in functions. The most essential ones are:

  • Data Types: int, float, str, bool, list, tuple, dict, set
  • Math: abs, max, min, sum, round, pow, divmod
  • Sequences: len, sorted, reversed, range, enumerate, zip
  • Logic: all, any, isinstance, type
  • I/O: print, input, open
  • Help: help, dir, callable, hasattr

Learn these well - they'll cover 90% of your needs!

โ† Chapter 02: Control Flow Next: Chapter 04 - Data Structures โ†’