Learn to Scode

4.Functions: Reusable Code Blocks

Learn how to create and use functions to organize your code and make it reusable.

30 minutes
Beginner
Article Content

What are Functions?

Functions are reusable blocks of code that perform specific tasks. They help you organize your code and avoid repetition.

Creating Functions

In Python, you define a function using the def keyword:

def greet(name):
    print(f"Hello, {name}!")

# Call the function
greet("Alice")  # Output: Hello, Alice!

Function Parameters

Functions can accept input values called parameters:

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

result = add_numbers(5, 3)  # result = 8

Return Values

Functions can return values using the return statement:

def calculate_area(length, width):
    area = length * width
    return area

rectangle_area = calculate_area(10, 5)  # 50

Default Parameters

You can provide default values for parameters:

def greet(name, greeting="Hello"):
    print(f"{greeting}, {name}!")

greet("Alice")           # Hello, Alice!
greet("Bob", "Hi")       # Hi, Bob!

Multiple Return Values

Functions can return multiple values:

def get_name_and_age():
    return "Alice", 25

name, age = get_name_and_age()
print(name)  # Alice
print(age)   # 25

Scope and Variables

Variables created inside a function are local to that function:

def my_function():
    local_var = "I'm local"
    print(local_var)

my_function()  # I'm local
# print(local_var)  # This would cause an error

🎯 Practice Exercise

Create a function that takes a list of numbers and returns the sum and average of those numbers.

Built-in Functions

Python comes with many useful built-in functions:

  • len() - Get the length of a sequence
  • max() - Find the maximum value
  • min() - Find the minimum value
  • sum() - Sum all values in a sequence
  • type() - Get the type of an object

Lambda Functions

Lambda functions are small, anonymous functions:

# Regular function
def square(x):
    return x ** 2

# Lambda function
square_lambda = lambda x: x ** 2

# Both do the same thing
print(square(5))        # 25
print(square_lambda(5)) # 25