All labs · lesson 8 of 9

Pythonintermediate35 min

Python Functions and Modules

Learn how to create reusable code with functions and organize your code with modules.

Edit any code block and press Run (or Ctrl/⌘ + Enter, or Shift + Enter). The code runs in your browser, so there is nothing to install. The first run downloads the language once; later runs are instant.

Functions help you write reusable, organized code. Let’s learn how to create and use them!

Defining Functions

A function is a block of code that only runs when called.

Exercise 1: Your First Function

# Create a function to greet someone
def greet(name):
    message = f"Hello, {name}! Welcome to Python."
    return message

result = greet("Alice")
print(result)
print(greet("Bob"))

Function Parameters

Functions can accept multiple parameters and have default values.

Exercise 2: Function with Multiple Parameters

# Create a function to calculate rectangle area
def calculate_area(length, width):
    area = length * width
    return area

# Test the function
area1 = calculate_area(5, 10)
area2 = calculate_area(7, 3)
print(f"Area 1: {area1}")
print(f"Area 2: {area2}")

Using Built-in Modules

Python comes with many useful modules. Let’s use the math module.

Exercise 3: Working with Math Module

# Use the math module
import math

radius = 5
circumference = 2 * math.pi * radius
area = math.pi * (radius ** 2)

print(f"Circumference: {circumference:.2f}")
print(f"Area: {area:.2f}")
print(f"Square root of 16: {math.sqrt(16)}")

Great job! You now understand functions and how to use Python modules.