Menu

Python Topic

Python Functions

1. Defining Functions

Purpose: To create a reusable block of code that performs a specific task.

Syntax:

python

def function_name():
    # code to execute
    # indented block

Example:

python

# Defining a simple function
def greet():
    print("Hello, world!")
    print("Welcome to Python!")

# Calling (using) the function
greet()
greet()  # You can call it multiple times

Output:

text

Hello, world!
Welcome to Python!
Hello, world!
Welcome to Python!

Key Points:

  • def is the keyword that defines a function

  • Function names should be descriptive and follow snake_case convention

  • Parentheses () are required

  • Colon : marks the start of the function body

  • The function body must be indented


2. Parameters (Arguments)

Purpose: To pass information into a function, making it more flexible and reusable.

Parameters vs Arguments:

  • Parameter: The variable listed in the function definition

  • Argument: The actual value passed to the function when called

python

# Function with parameters
def greet_person(name, age):  # 'name' and 'age' are parameters
    print(f"Hello, {name}! You are {age} years old.")

# Calling with arguments
greet_person("Alice", 25)  # "Alice" and 25 are arguments
greet_person("Bob", 30)    # Different arguments

Output:

text

Hello, Alice! You are 25 years old.
Hello, Bob! You are 30 years old.

Types of Parameters:

Positional Arguments: Must be in the same order as parameters

python

def describe_pet(animal_type, pet_name):
    print(f"I have a {animal_type} named {pet_name}.")

describe_pet("dog", "Rex")  # Order matters!

Keyword Arguments: Specify which parameter gets which value

python

describe_pet(pet_name="Whiskers", animal_type="cat")  # Order doesn't matter

Default Parameters: Give parameters default values

python

def describe_pet(pet_name, animal_type="dog"):  # animal_type has default value
    print(f"I have a {animal_type} named {pet_name}.")

describe_pet("Rex")           # Uses default: "dog"
describe_pet("Fluffy", "cat") # Overrides default

3. Return Values

Purpose: To send data back from a function to where it was called.

Syntax: return expression

python

# Function that returns a value
def add_numbers(a, b):
    result = a + b
    return result  # Sends the result back

# Using the return value
sum_result = add_numbers(5, 3)
print(f"The sum is: {sum_result}")  # Output: The sum is: 8

# You can use the return value directly
print(f"10 + 15 = {add_numbers(10, 15)}")  # Output: 10 + 15 = 25

Multiple Return Values:

python

def calculate_rectangle(length, width):
    area = length * width
    perimeter = 2 * (length + width)
    return area, perimeter  # Returns a tuple

# Unpacking the returned values
rect_area, rect_perimeter = calculate_rectangle(5, 3)
print(f"Area: {rect_area}, Perimeter: {rect_perimeter}")
# Output: Area: 15, Perimeter: 16

The None Return Value:

If a function doesn't have a return statement, it automatically returns None

python

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

result = say_hello("Charlie")
print(result)  # Output: None

4. Scope

Purpose: Scope determines where in your program a variable can be accessed.

Local Scope: Variables defined inside a function

python

def my_function():
    local_var = "I'm local"  # Local variable
    print(local_var)  # This works

my_function()
# print(local_var)  # This would cause an ERROR - local_var doesn't exist outside
Global Scope: Variables defined outside any function
python

global_var = "I'm global"  # Global variable

def show_global():
    print(global_var)  # Can access global variables

show_global()  # Output: I'm global
print(global_var)  # Also works outside function
The global Keyword: Modifying global variables from inside a function
python

counter = 0

def increment():
    global counter  # Tell Python we want to use the global variable
    counter += 1

print(f"Before: {counter}")  # Output: Before: 0
increment()
increment()
print(f"After: {counter}")   # Output: After: 2

It's generally better practice to avoid modifying global variables inside functions. Instead, pass values as parameters and return results.


5. Putting It All Together: Practical Examples

Example 1: Calculator Functions

python

def calculator(a, b, operation):
    """A simple calculator function."""
    if operation == "add":
        return a + b
    elif operation == "subtract":
        return a - b
    elif operation == "multiply":
        return a * b
    elif operation == "divide":
        if b != 0:
            return a / b
        else:
            return "Error: Division by zero"
    else:
        return "Error: Invalid operation"

# Using the calculator
result1 = calculator(10, 5, "add")
result2 = calculator(10, 5, "divide")
print(f"10 + 5 = {result1}")  # Output: 10 + 5 = 15
print(f"10 / 5 = {result2}")  # Output: 10 / 5 = 2.0

Example 2: Data Validation Function

python

def validate_password(password):
    """Validate if a password meets security requirements."""
    if len(password) < 8:
        return False, "Password must be at least 8 characters long"
    
    if not any(char.isdigit() for char in password):
        return False, "Password must contain at least one number"
    
    if not any(char.isupper() for char in password):
        return False, "Password must contain at least one uppercase letter"
    
    return True, "Password is valid"

# Testing the function
passwords = ["short", "nouppercase1", "GoodPass123"]
for pwd in passwords:
    is_valid, message = validate_password(pwd)
    status = "✓" if is_valid else "✗"
    print(f"{status} '{pwd}': {message}")

Example 3: Temperature Converter

python

def celsius_to_fahrenheit(celsius):
    """Convert Celsius to Fahrenheit."""
    return (celsius * 9/5) + 32

def fahrenheit_to_celsius(fahrenheit):
    """Convert Fahrenheit to Celsius."""
    return (fahrenheit - 32) * 5/9

def convert_temperature(temp, unit):
    """Main conversion function with input validation."""
    if unit.upper() == "C":
        return celsius_to_fahrenheit(temp), "F"
    elif unit.upper() == "F":
        return fahrenheit_to_celsius(temp), "C"
    else:
        return None, "Error: Invalid unit. Use 'C' or 'F'"

# Using the temperature converter
temp = 25
converted_temp, new_unit = convert_temperature(temp, "C")
print(f"{temp}°C = {converted_temp:.1f}°{new_unit}")
# Output: 25°C = 77.0°F

Key Benefits of Using Functions:

  1. Reusability: Write once, use many times

  2. Modularity: Break complex problems into smaller, manageable pieces

  3. Readability: Well-named functions make code self-documenting

  4. Debugging: Easier to find and fix bugs in small, focused functions

  5. Testing: Individual functions can be tested separately

 

Comments (0)

No comments yet. Be the first to comment!

LecturreAI Assistant

Hello! I'm LecturreAI

What would you like to learn today?