Functions in Python: My Personal Guide¶

Author: Mohammad Sayem Chowdhury

Welcome! In this notebook, I'll share my journey learning about functions in Python. Functions are one of my favorite features because they help organize code and make it reusable. By the end, you'll understand how I approach creating and using functions.

What I'll Cover¶

  • Understanding Functions
  • Variables and Scope
  • Pre-defined vs Custom Functions
  • Control Flow in Functions
  • Default Arguments
  • Global vs Local Variables

Estimated time: about 40 minutes of focused learning.


My Understanding of Functions¶

I think of functions as little machines that take inputs, do something useful, and give back outputs. They're like recipes - you follow the same steps but can use different ingredients each time.

There are two main types:

  • Built-in functions: Python gives us these (like print(), len())
  • Custom functions: We create these ourselves

Creating My First Function¶

Here are the rules I follow when defining functions:

  • Start with def followed by the function name and parentheses ()
  • Put input parameters inside the parentheses
  • Use a colon : to start the function body
  • Indent the code inside the function
  • Use return to send back a result

Let me create a simple function:

In [ ]:
# My first function - adds 1 to any number
def add_one(number):
    result = number + 1
    print(f"{number} plus one equals {result}")
    return result

I can get help about my function:

In [ ]:
# Getting help about my function
help(add_one)

Now I can use my function with different inputs:

In [ ]:
# Testing my function
add_one(5)
In [ ]:
# Trying with a different number
add_one(10)

Let me create a more complex function that takes two parameters:

In [ ]:
# Function to multiply two numbers
def multiply_numbers(first_num, second_num):
    product = first_num * second_num
    return product

The beauty of functions is their flexibility - they work with different data types:

In [ ]:
# Multiplying integers
multiply_numbers(4, 7)
In [ ]:
# Multiplying floats
multiply_numbers(3.14, 2.0)
In [ ]:
# Even works with strings and numbers!
multiply_numbers(3, "Hello! ")

Variables in Functions: My Approach¶

I need to understand the difference between local and global variables:

  • Local variables: Created inside a function, only exist within that function
  • Global variables: Created outside functions, accessible everywhere
In [ ]:
# Example of local vs global variables
global_var = "I'm accessible everywhere"

def demonstrate_scope():
    local_var = "I only exist in this function"
    print(f"Inside function - Global: {global_var}")
    print(f"Inside function - Local: {local_var}")
    return local_var

# Call the function
result = demonstrate_scope()
print(f"Outside function - Global: {global_var}")
# print(local_var)  # This would cause an error!

Working with Pre-defined Functions¶

Python gives us many useful built-in functions. Here are some I use frequently:

In [ ]:
# Some of my favorite built-in functions
my_list = [1, 5, 3, 9, 2]

print(f"Length: {len(my_list)}")
print(f"Sum: {sum(my_list)}")
print(f"Max: {max(my_list)}")
print(f"Min: {min(my_list)}")
print(f"Sorted: {sorted(my_list)}")

Adding Control Flow to Functions¶

I can make functions smarter by adding if/else statements and loops:

In [ ]:
# Function with conditional logic
def check_even_odd(number):
    if number % 2 == 0:
        return f"{number} is even"
    else:
        return f"{number} is odd"

# Testing my function
print(check_even_odd(4))
print(check_even_odd(7))
In [ ]:
# Function with a loop
def count_up_to(limit):
    result = []
    for i in range(1, limit + 1):
        result.append(i)
    return result

# Testing the counting function
print(count_up_to(5))

Default Arguments: Making Functions Flexible¶

I love using default arguments - they make functions more user-friendly:

In [ ]:
# Function with default arguments
def greet_person(name, greeting="Hello", punctuation="!"):
    return f"{greeting}, {name}{punctuation}"

# Using the function different ways
print(greet_person("Mohammad"))
print(greet_person("Mohammad", "Hi"))
print(greet_person("Mohammad", "Hey", "."))

Working with Global Variables¶

Sometimes I need to modify global variables from within functions:

In [ ]:
# Global variable example
counter = 0

def increment_counter():
    global counter
    counter += 1
    print(f"Counter is now: {counter}")

def reset_counter():
    global counter
    counter = 0
    print("Counter reset to 0")

# Testing global variable manipulation
increment_counter()
increment_counter()
increment_counter()
reset_counter()

Advanced Function Examples¶

Here are some more sophisticated functions I've created:

In [ ]:
# Function that returns multiple values
def analyze_numbers(numbers):
    total = sum(numbers)
    average = total / len(numbers)
    maximum = max(numbers)
    minimum = min(numbers)
    return total, average, maximum, minimum

# Using the function
my_numbers = [10, 20, 30, 40, 50]
total, avg, max_val, min_val = analyze_numbers(my_numbers)

print(f"Total: {total}")
print(f"Average: {avg}")
print(f"Maximum: {max_val}")
print(f"Minimum: {min_val}")
In [ ]:
# Function that processes a list of names
def format_names(names, style="title"):
    formatted = []
    for name in names:
        if style == "upper":
            formatted.append(name.upper())
        elif style == "lower":
            formatted.append(name.lower())
        else:  # title case
            formatted.append(name.title())
    return formatted

# Testing different formatting styles
name_list = ["mohammad", "sarah", "JOHN", "alice"]
print("Title case:", format_names(name_list))
print("Upper case:", format_names(name_list, "upper"))
print("Lower case:", format_names(name_list, "lower"))

Practice Exercises¶

Let me create some functions to practice different concepts:

In [ ]:
# Exercise 1: Temperature converter
def celsius_to_fahrenheit(celsius):
    fahrenheit = (celsius * 9/5) + 32
    return fahrenheit

def fahrenheit_to_celsius(fahrenheit):
    celsius = (fahrenheit - 32) * 5/9
    return celsius

# Testing temperature conversion
print(f"25°C = {celsius_to_fahrenheit(25)}°F")
print(f"77°F = {fahrenheit_to_celsius(77)}°C")
In [ ]:
# Exercise 2: List manipulator
def process_list(my_list, operation="sum"):
    if operation == "sum":
        return sum(my_list)
    elif operation == "product":
        result = 1
        for num in my_list:
            result *= num
        return result
    elif operation == "average":
        return sum(my_list) / len(my_list)
    else:
        return "Unknown operation"

# Testing list operations
test_list = [2, 4, 6, 8]
print(f"Sum: {process_list(test_list, 'sum')}")
print(f"Product: {process_list(test_list, 'product')}")
print(f"Average: {process_list(test_list, 'average')}")

My Key Takeaways¶

Functions have transformed how I write Python code. They help me:

  • Organize code into logical chunks
  • Avoid repeating myself
  • Make code easier to test and debug
  • Create reusable solutions

The concept of scope (local vs global variables) was initially confusing, but now I appreciate how it helps keep code organized and prevents unexpected interactions between different parts of my program.

Copyright © 2025 Mohammad Sayem Chowdhury. This notebook and its content are shared for personal learning and inspiration.


Next Steps in My Function Journey¶

I'm excited to explore more advanced topics like lambda functions, decorators, and generators. Functions are the building blocks of larger programs, and mastering them opens up so many possibilities!

— Mohammad Sayem Chowdhury