Python Tutorial

Functions and Modules

Create reusable functions, pass arguments, return values and organize code across modules.

Concept

Functions package a task behind a name. Parameters receive input and return statements send a result back to the caller. Small focused functions are easier to test and reuse.

Modules let you split code across files. Import only what you need and avoid hidden global dependencies when possible.

Example

def calculate_total(price, quantity=1):
    return price * quantity

print(calculate_total(750, 2))
print(calculate_total(500))
Type the example yourself and change at least one value. Small experiments reveal syntax and behavior faster than passive reading.

Practice Tasks

  1. Write a function that returns whether a number is even.
  2. Write a function that returns the largest of three numbers.
  3. Create a second .py file and import one function from it.

Key Takeaways

  • Functions reduce duplication.
  • Return values are easier to compose than printing inside every function.
  • Modules organize growing programs.