Python Beginner

Python Functions: Creating Reusable Code Blocks

CodingerWeb
CodingerWeb
22 views 30 min read

Understanding Python Functions

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

Creating Functions

Use the def keyword to create functions:


# Basic function
def greet():
    print("Hello, World!")

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

# Function with parameters
def greet_person(name):
    print(f"Hello, {name}!")

greet_person("Alice")  # Output: Hello, Alice!
greet_person("Bob")    # Output: Hello, Bob!

Function Parameters and Arguments


# Multiple parameters
def add_numbers(a, b):
    result = a + b
    print(f"{a} + {b} = {result}")

add_numbers(5, 3)  # Output: 5 + 3 = 8

# Default parameters
def greet_with_title(name, title="Mr."):
    print(f"Hello, {title} {name}!")

greet_with_title("Smith")           # Output: Hello, Mr. Smith!
greet_with_title("Johnson", "Dr.")  # Output: Hello, Dr. Johnson!

# Keyword arguments
def create_profile(name, age, city="Unknown"):
    print(f"Name: {name}")
    print(f"Age: {age}")
    print(f"City: {city}")

create_profile(name="Alice", age=25, city="New York")
create_profile(age=30, name="Bob")  # Order doesn't matter with keywords

Return Values

Functions can return values using the return statement:


# Function that returns a value
def add(a, b):
    return a + b

result = add(5, 3)
print(result)  # Output: 8

# Function with multiple return values
def get_name_parts(full_name):
    parts = full_name.split()
    first_name = parts[0]
    last_name = parts[-1]
    return first_name, last_name

first, last = get_name_parts("John Doe")
print(f"First: {first}, Last: {last}")

# Function with conditional returns
def check_grade(score):
    if score >= 90:
        return "A"
    elif score >= 80:
        return "B"
    elif score >= 70:
        return "C"
    elif score >= 60:
        return "D"
    else:
        return "F"

grade = check_grade(85)
print(f"Grade: {grade}")  # Output: Grade: B

Variable Scope

Variables have different scopes (where they can be accessed):


# Global variable
global_var = "I'm global"

def my_function():
    # Local variable
    local_var = "I'm local"
    print(global_var)  # Can access global variable
    print(local_var)   # Can access local variable

my_function()
print(global_var)  # Can access global variable
# print(local_var)  # Error! Cannot access local variable outside function

# Modifying global variables
counter = 0

def increment():
    global counter
    counter += 1

increment()
print(counter)  # Output: 1

Lambda Functions

Lambda functions are small, anonymous functions:


# Lambda function
square = lambda x: x ** 2
print(square(5))  # Output: 25

# Lambda with multiple parameters
add = lambda x, y: x + y
print(add(3, 4))  # Output: 7

# Using lambda with built-in functions
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))
print(squared)  # Output: [1, 4, 9, 16, 25]

# Filter with lambda
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)  # Output: [2, 4]

Docstrings

Document your functions with docstrings:


def calculate_area(length, width):
    """
    Calculate the area of a rectangle.
    
    Args:
        length (float): The length of the rectangle
        width (float): The width of the rectangle
    
    Returns:
        float: The area of the rectangle
    """
    return length * width

# Access docstring
print(calculate_area.__doc__)
help(calculate_area)

Practice Exercise

Create a calculator with functions:


def add(x, y):
    """Add two numbers"""
    return x + y

def subtract(x, y):
    """Subtract two numbers"""
    return x - y

def multiply(x, y):
    """Multiply two numbers"""
    return x * y

def divide(x, y):
    """Divide two numbers"""
    if y != 0:
        return x / y
    else:
        return "Error: Division by zero!"

def calculator():
    """Simple calculator function"""
    print("Simple Calculator")
    print("Operations: +, -, *, /")
    
    while True:
        try:
            num1 = float(input("Enter first number: "))
            operation = input("Enter operation (+, -, *, /) or 'q' to quit: ")
            
            if operation == 'q':
                break
                
            num2 = float(input("Enter second number: "))
            
            if operation == '+':
                result = add(num1, num2)
            elif operation == '-':
                result = subtract(num1, num2)
            elif operation == '*':
                result = multiply(num1, num2)
            elif operation == '/':
                result = divide(num1, num2)
            else:
                print("Invalid operation!")
                continue
                
            print(f"Result: {result}")
            
        except ValueError:
            print("Please enter valid numbers!")

# Run the calculator
calculator()