Defining and Calling Functions

20 min In Progress

Learning Objectives

  • Define a function with def
  • Pass parameters and return values
  • Understand local vs global scope

Creating a Function

Use the def keyword followed by a name and parentheses. The indented block is the function body.

def greet(name):
    message = f"Hello, {name}!"
    return message

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

Parameters and Return

Functions can accept multiple inputs and return a single output.

def rectangle_area(width, height):
    return width * height

area = rectangle_area(5, 3)
print(f"Area: {area}")

Default Parameters

You can provide default values for parameters.

def power(base, exponent=2):
    return base ** exponent

print(power(3))      # 9
print(power(2, 3))   # 8

📝 Exercise: Greeting Generator

Write a function called greet that takes a name and a greeting ('Hello' by default) and returns the full greeting string.

code.py
Output

            
← Back to Chapter