5Lesson 5 of 5

Functions in Python

Learn how to create and use functions in Python to organize code and avoid repetition.

A function is a block of code that only runs when it is called. As a result, a function can return data. Functions help avoid code repetition and make the program more organized and easier to maintain.

What is a Function?

In Python, a function is defined using the 'def' keyword, followed by a function name and parentheses. Inside the parentheses, we can place parameters that the function will accept. After the parentheses, we put a colon ':' and the function code must be indented.

# Defining a function
def my_function():
    print("Hello from a function!")

# Calling the function
my_function()
The function must be defined before it is called. The function name should be descriptive and follow naming conventions (snake_case).

Functions with Parameters

Parameters are variables listed inside the parentheses in the function definition. When we call the function, we give values to those parameters - these values are called arguments.

# Function that prints the user's name
def print_users_name(name):
    print(f"Hello {name}")
    print("Today we will learn functions in Python")
    print("Get your laptop ready and listen to the lesson")

# Calling the function with an argument
name = input("Name: ")
print_users_name(name)

Multiple Parameters

Functions can accept more than one parameter. Parameters are separated by commas inside the parentheses.

# Function to calculate rectangle area
def rec_area(a, b):  # a, b are parameters
    area_calculated = a * b
    print(area_calculated)

# Calling the function with two arguments
rec_area(5, 10)  # 5 and 10 are arguments
# Output: 50
Parameters are the variable names in the function definition. Arguments are the actual values we give when calling the function.

Return Statement

The 'return' keyword is used to return a value from the function. When return is executed, the function ends immediately and the value is returned to the caller.

# Function that returns the sum of two numbers
def add(x, y):
    return x + y

# Storing the result in a variable
result = add(5, 10)
print(result)  # 15

# Or directly in print
print(add(3, 7))  # 10

Return vs Print

It is important to understand the difference between return and print. Print simply displays something on the screen, while return returns a value that can be used later in the program.

# Function with print - returns nothing
def printHello():
    print("Hello!")

results = printHello()  # Prints "Hello!"
print(results)  # None - because the function didn't return anything

# Function with return - returns a value
def getHello():
    return "Hello!"

results = getHello()  # Doesn't print anything
print(results)  # "Hello!" - the returned value
If a function doesn't have a return statement, it automatically returns None.

Practical Examples

Let's look at some practical examples of functions for various mathematical operations.

# Functions for mathematical operations
def subtract(x, y):
    return x - y

def multiply(x, y):
    return x * y

def divide(x, y):
    if y != 0:
        return x / y
    else:
        return "Cannot divide by zero"

# Usage
print(subtract(10, 3))    # 7
print(multiply(4, 5))     # 20
print(divide(20, 4))      # 5.0
print(divide(10, 0))      # Cannot divide by zero

Functions with String Manipulation

Functions can work with any data type, including strings. Here's an example that capitalizes the first and last name.

# Function that capitalizes the full name
def capitalize_name(first_name, last_name):
    new_first = first_name.capitalize()
    new_last = last_name.capitalize()
    return f"{new_first} {new_last}"

# Usage
result = capitalize_name("john", "doe")
print(result)  # John Doe
The capitalize() method returns the string with the first character uppercase and the rest lowercase.

Key Takeaways

  • Functions are defined with the 'def' keyword and called by their name
  • Parameters are variables in the definition, arguments are actual values
  • Return returns a value from the function, print only displays on screen
  • Functions help organize code and avoid repetition
  • A function without return automatically returns None

Practice Exercises

  1. Create the average(grades) function that takes a list of grades and calculates the average with for (if list is empty, return None)
  2. Create the find_max(nums) function that returns the largest number without using max()
  3. Create the greater_than(nums, limit) function that returns a new list with only numbers > limit
  4. Create the calc(a, b, op) function that performs mathematical operations based on the given operator
  5. Build a Mini Bank System with deposit(), withdraw(), and check_balance() functions