Python Full Tutorial — Part 7: Functions

By Suraj Ahir December 25, 2025 6 min read

Python — Python Error Handling
Python — Python Error Handling
← Part 6 Python Tutorial · Part 7 of 12 Part 8 →

Functions are how you stop writing the same logic over and over. They are how you organize code, make it testable, and build programs that scale. Every professional Python codebase is built from functions. This is one of the most important parts of the entire series.

Defining and Calling a Function

Basic Function
def greet():
    print("Hello from SRJahir Tech!")
    print("Welcome to Python!")

greet()   # Call the function
greet()   # Call it again — reusable

Functions with Parameters

Parameters and Arguments
def greet_user(name, city):
    print(f"Hello {name}! You are from {city}.")

greet_user("Suraj", "Rajkot")
greet_user("Priya", "Mumbai")

Return Values

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

result = calculate_area(10, 5)
print(f"Area: {result} sq units")

# Return multiple values
def get_min_max(numbers):
    return min(numbers), max(numbers)

low, high = get_min_max([3, 7, 1, 9, 4])
print(f"Min: {low}, Max: {high}")

Default Parameter Values

Default Parameters
def send_email(to, subject, priority="normal"):
    print(f"To: {to}")
    print(f"Subject: {subject}")
    print(f"Priority: {priority}")

send_email("admin@example.com", "Server down!", "high")
send_email("user@example.com", "Newsletter")  # Uses default priority

*args — Variable Number of Arguments

*args Example
def total(*numbers):
    return sum(numbers)

print(total(10, 20))           # 30
print(total(5, 15, 25, 35))    # 80

**kwargs — Keyword Arguments

**kwargs Example
def create_profile(**info):
    for key, value in info.items():
        print(f"{key}: {value}")

create_profile(name="Suraj", age=22, city="Rajkot", role="Engineer")

Lambda Functions

Lambda functions are small anonymous functions — one line, no def needed:

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

# Used with sorted/filter/map
students = [("Amit", 85), ("Sara", 92), ("Raj", 78)]
sorted_students = sorted(students, key=lambda s: s[1], reverse=True)
print(sorted_students)  # Sorted by score, highest first

Scope — Local vs Global

Scope Example
total_users = 0  # Global variable

def add_user():
    global total_users   # Declare we want the global one
    total_users += 1

add_user()
add_user()
print(total_users)  # 2

Best practice: avoid global variables when possible. Pass values as parameters and return results. Functions with no side effects are easier to test and debug.

In Part 8, we learn file handling — reading and writing files, which is how programs persist data beyond a single run.

Common Mistakes Beginners Make

Learning from common pitfalls saves hours of frustration. Here are the mistakes most beginners make in this area and how to avoid them.

The first mistake is trying to memorize syntax before understanding logic. Python syntax is simple — you could memorize it in a day. But if you do not understand why you are writing what you are writing, you will not be able to adapt when things change or when a problem looks slightly different. Always ask: what problem does this solve?

The second mistake is writing very long functions or very long scripts without breaking them into logical units. Real professional code is made of small, focused pieces that each do one thing well. The moment your code does two or three unrelated things in one block, it is time to split it up.

The third mistake is not reading error messages. Python's error messages are actually quite good. They tell you the file, the line number, the type of error, and often a description. Read the entire error before searching online. The answer is usually right there.

How This Topic Appears in Real Projects

In real codebases, every concept from this tutorial series appears constantly. Backend web applications built with Flask or Django use functions, classes, data structures, and error handling throughout every route and service. Data pipelines use loops and comprehensions to process thousands of records efficiently. CLI tools use argument parsing, file handling, and process management. DevOps automation scripts combine shell integration with Python logic to orchestrate deployments, monitor systems, and handle alerts.

The concepts that feel abstract right now will click into place the moment you start building something real. That is why the best way to learn is to pick a small project that solves a problem you actually have — even something simple like a personal expense tracker or a file organizer — and build it using everything you have learned so far.

Practice Exercise

Before moving to the next part, write a small program that uses what you learned in this section. Do not copy from anywhere. Start with a blank file and build it from memory. The struggle is the learning. If you get stuck, read the code examples again — do not just copy them. Understand each line, then close the examples and write the program yourself. This is how programming actually sticks.

Lambda Functions for Short Operations

Python supports anonymous functions — small, one-expression functions defined without a name using the lambda keyword. Lambda functions are most useful when you need a simple function as an argument to another function:

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

# Equivalent lambda
square = lambda x: x ** 2

# Most common use: as argument to sorted(), map(), filter()
students = [("Alice", 88), ("Bob", 95), ("Charlie", 72)]

# Sort by score (second element of each tuple)
sorted_students = sorted(students, key=lambda s: s[1], reverse=True)
# Result: [("Bob", 95), ("Alice", 88), ("Charlie", 72)]

# Filter scores above 80
passing = list(filter(lambda s: s[1] >= 80, students))
# Result: [("Alice", 88), ("Bob", 95)]

Use lambda for simple, single-expression functions. For anything complex enough to need explanation or multiple lines, define a regular function with a descriptive name instead.

The Importance of Docstrings

Professional Python functions include docstrings — string literals immediately after the function definition that document what the function does, its parameters, and its return value. Docstrings are accessible via help() and are used by documentation tools to auto-generate API documentation. Writing clear docstrings is a sign of professional-quality code and makes your functions usable by others (including future you).

Practice Exercise

Write a set of utility functions for a simple student grade management system: a function to calculate the average of a list of scores, a function to determine letter grade from a numeric score, a function that takes a list of (name, score) tuples and returns a sorted list of (name, letter_grade) pairs. Write proper docstrings for each function and test them with at least five sample students.

Disclaimer: This content is for educational purposes only. SRJahir Tech does not guarantee any specific outcome, job placement, or exam result. Learning requires consistent effort and practical application.