► Overview

/code

Simple function

def greet():
print(“Hello, World!”)

greet() # Call the function

Function with parameters

def greet_person(name):
print(f”Hello, {name}!”)

greet_person(“Alice”)
greet_person(“Bob”)

Function with return value

def add_numbers(a, b):
result = a + b
return result

total = add_numbers(5, 3)
print(“Sum:”, total)

Output:
Hello, World!
Hello, Alice!
Hello, Bob!
Sum: 8

► Important Points

✓ Functions make code reusable and organized
✓ Use descriptive names for functions
✓ Keep functions focused on single tasks
✓ Parameters make functions flexible
✓ return sends data back to the caller
✓ Functions can call other functions

► Remember

✓ Define with def, followed by function name and ()
✓ Indent the function body
✓ Call functions by name with ()
✓ Functions don’t run until called
✓ Use functions to avoid code repetition

■ Practice Challenge

  1. Create a function that calculates the area of a rectangle
  2. Write a function that checks if a number is even or odd
  3. Make a function that converts temperature from Celsius to Fahrenheit

Functions are reusable blocks of code that perform specific tasks. They help organize code, reduce repetition, and make programs more maintainable. Functions take inputs (parameters), process them, and can return outputs.

► Real-World Analogy

Think of a coffee machine:
» Input: Coffee beans + water
» Process: Brew coffee
» Output: Hot coffee
» Can use it repeatedly without rebuilding the machine

► Key Concepts

✓ def keyword: Defines a function
✓ Function name: Describes what it does
✓ Parameters: Inputs the function accepts
✓ Function body: Code that executes
✓ return: Sends result back to caller
✓ DRY principle: Don’t Repeat Yourself

■ Function Examples