Selected topic

Functions and Modules

Functions

Prefer practical output? Use related tools below while reading.

Functions

A function is a block of code that can be executed multiple times from different parts of your program. It takes input(s), performs some operations, and returns output.

Example:

python
def greet(name):
"""Prints a personalized greeting"""
print(f"Hello, {name}!")

# Call the function with an argument
greet("John") # Output: Hello, John!


In this example:

  • We define a function greet that takes one input parameter name.
  • Inside the function, we use an f-string to create a greeting message.
  • The print() statement is used to output the greeting.
  • To call the function, we simply invoke it with the desired argument ("John").

Modules

A module is a file containing Python code that can be imported into your program. Modules provide reusable code, functions, and variables that you can use in your own programs.

Example:

python
# mymodule.py (a simple module)
def add(a, b):
"""Returns the sum of two numbers"""
return a + b

x = 5
y = 3

result = add(x, y)

print(result) # Output: 8


In this example:

  • We create a file mymodule.py containing a function add.
  • The add function takes two input parameters and returns their sum.
  • In our main program (not shown), we import the mymodule module using import mymodule.
  • We can then call the add function from the imported module, passing arguments as needed.
To use a module in your own code:
  1. Save the module file (mymodule.py, for example) in the same directory as your main program.
  2. In your main program, import the module using import mymodule.
  3. Call functions or access variables from the imported module as needed.

Example with both Functions and Modules

Suppose we have a simple calculator that performs arithmetic operations:
python
# mycalculator.py (a module)
def add(a, b):
    """Returns the sum of two numbers"""
    return a + b

def subtract(a, b):
"""Returns the difference between two numbers"""
return a - b

def multiply(a, b):
"""Returns the product of two numbers"""
return a * b


Now, in our main program:
python
import mycalculator as mc

# Define some values
a = 5
b = 3

# Perform calculations using functions from the imported module
result1 = mc.add(a, b)
result2 = mc.subtract(a, b)

print(f"Result 1: {result1}")
print(f"Result 2: {result2}")

# Use another function from the same module
product = mc.multiply(a, b)
print(f"Product of {a} and {b}: {product}")


In this example:

  • We import the mymodule (renamed to mc) using import mycalculator as mc.
  • We define some values (a and b).
  • We use functions from the imported module to perform calculations.
  • We can also access variables or other functions from the same module as needed.