Python Basics — Defining Functions

2 minute read

Defining Functions

A function is a named block of code that you can call whenever needed. Python uses the def keyword to define functions.

Basic Syntax

def function_name():
    """Optional docstring."""
    # function body
    pass
def say_hello():
    print("Hello, World!")

say_hello()  # Hello, World!
say_hello()  # Hello, World!

Function Naming Conventions

Follow PEP 8:

# ✅ Good — snake_case
def calculate_total():
    pass

def get_user_name():
    pass

# ❌ Bad
def CalculateTotal():   # PascalCase is for classes
    pass

def calculatetotal():   # hard to read
    pass

Return Values

Returning a Single Value

def square(n):
    return n ** 2

result = square(5)
print(result)  # 25

Returning Multiple Values

Python functions can return multiple values as a tuple:

def divide(a, b):
    quotient = a // b
    remainder = a % b
    return quotient, remainder

q, r = divide(17, 5)
print(f"17 ÷ 5 = {q} remainder {r}")
# 17 ÷ 5 = 3 remainder 2

Returning None

If a function has no return statement (or just return with no value), it returns None:

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

result = greet("Alice")
print(result)  # None
def check(x):
    if x > 0:
        return "positive"
    # Falls off end → returns None

print(check(5))   # positive
print(check(-1))  # None

Functions Without return

Functions that don’t return a value perform actions (side effects):

def print_separator(char="-", width=40):
    print(char * width)

print_separator()      # ----------------------------------------
print_separator("=")   # ========================================

Calling Functions

def add(a, b):
    return a + b

# Direct call
result = add(3, 5)
print(result)  # 8

# Use in expressions
total = add(10, 20) + add(30, 40)
print(total)  # 100

# Pass result to another function
print(add(1, 2))  # 3

Functions Are Objects

In Python, functions are first-class objects — they can be assigned to variables, stored in collections, and passed as arguments:

def multiply(a, b):
    return a * b

# Assign to a variable
operation = multiply
print(operation(3, 4))  # 12

# Store in a list
operations = [add, multiply]
for op in operations:
    print(op(5, 3))
# 8
# 15

Common Mistakes

Forgetting Parentheses

def get_pi():
    return 3.14159

# ❌ This references the function object, doesn't call it
print(get_pi)    # <function get_pi at 0x...>

# ✅ Call with parentheses
print(get_pi())  # 3.14159

Forgetting return

# ❌ Forgot return — function returns None
def add_bad(a, b):
    result = a + b  # computed but never returned

print(add_bad(3, 5))  # None

# ✅ Return the result
def add_good(a, b):
    return a + b

print(add_good(3, 5))  # 8

Summary

  • Define with def function_name():
  • Use snake_case for function names
  • return sends a value back to the caller
  • Multiple values returned as a tuple
  • No return → function returns None
  • Functions are first-class objects in Python

Next up: Parameters & Return →

Updated: