Imagine: you wrote code to calculate a discount. That code is needed in 10 places in your program!
Bad approach: Copy-paste it 10 times → find a bug → fix it in 10 places 😰
Good approach: Create a function → use it 10 times → fix it in one place! 🚀
Functions are the foundation of professional programming!
🤔 What Is a Function?
A function is a named block of code that can be called multiple times.
Functions you already know:
print("Hello") # Output function
len("Python") # Length function
input("Name: ") # Input function
range(10) # Number generation function
These are all built-in Python functions. Now let’s learn to create our own!
📝 Defining a Function — Syntax
Basic syntax:
def function_name():
code
code
return result # optional
Elements:
- def — keyword (short for “define”)
- function_name — your choice of name
- () — parentheses for parameters (empty for now)
- : — colon is required!
- Code — indented
Simplest example:
def say_hello():
print("Hello!")
print("How are you?")
# Calling the function:
say_hello()
# Output:
# Hello!
# How are you?
Calling it multiple times:
say_hello() # First call
say_hello() # Second call
say_hello() # Third call
# The code runs 3 times!
📦 Parameters — Passing Data into a Function
Parameters let a function work with different data.
One parameter:
def greet(name):
print(f"Hello, {name}!")
greet("Anna") # Hello, Anna!
greet("Bob") # Hello, Bob!
greet("Sveta") # Hello, Sveta!
name is a parameter (in the function definition)
“Anna” is an argument (when calling the function)
Multiple parameters:
def introduce(name, age, city):
print(f"My name is {name}")
print(f"I am {age} years old")
print(f"I am from {city}")
introduce("Anna", 16, "New York")
# My name is Anna
# I am 16 years old
# I am from New York
Default parameter values:
def greet(name="Guest"):
print(f"Hello, {name}!")
greet() # Hello, Guest!
greet("Anna") # Hello, Anna!
If no argument is passed → the default value is used.
Keyword arguments:
def create_profile(name, age, city):
print(f"{name}, {age}, {city}")
# Order doesn't matter:
create_profile(age=16, city="New York", name="Anna")
# Anna, 16, New York
🔄 return — Returning a Value
return lets a function send a result back to the caller!
Without return (only printing):
def add(a, b):
print(a + b)
add(5, 3) # Prints 8, but returns nothing
result = add(5, 3)
print(result) # None ❌
With return (returning the result):
def add(a, b):
return a + b
result = add(5, 3) # result = 8 ✅
print(result) # 8
The difference is critical!
- print() — displays on screen
- return — sends a value back for use in code
return stops the function:
def check_age(age):
if age < 18:
return "Minor" # Exits here!
# This part doesn't run if age < 18:
return "Adult"
status = check_age(16)
print(status) # Minor
Multiple return statements:
def get_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 = get_grade(85)
print(f"Grade: {grade}") # Grade: B
Returning multiple values:
def get_user_info():
name = "Anna"
age = 16
city = "New York"
return name, age, city # Returns a tuple
# Unpacking:
user_name, user_age, user_city = get_user_info()
print(user_name) # Anna
print(user_age) # 16
print(user_city) # New York
🎯 Useful Function Examples
1. Calculator:
def calculate(a, b, operation):
if operation == "+":
return a + b
elif operation == "-":
return a - b
elif operation == "*":
return a * b
elif operation == "/":
if b != 0:
return a / b
else:
return "Error: division by zero"
else:
return "Unknown operation"
result = calculate(10, 5, "+")
print(result) # 15
2. Even check:
def is_even(number):
return number % 2 == 0
if is_even(10):
print("10 is even")
else:
print("10 is odd")
# 10 is even
3. Finding the maximum:
def find_max(a, b, c):
if a >= b and a >= c:
return a
elif b >= a and b >= c:
return b
else:
return c
maximum = find_max(5, 12, 7)
print(f"Maximum: {maximum}") # Maximum: 12
4. Password validation:
def is_password_strong(password):
if len(password) < 8:
return False
has_digit = any(char.isdigit() for char in password)
has_letter = any(char.isalpha() for char in password)
return has_digit and has_letter
if is_password_strong("abc123"):
print("✅ Password is strong")
else:
print("❌ Password is weak")
5. Temperature converter:
def celsius_to_fahrenheit(celsius):
return (celsius * 9/5) + 32
def fahrenheit_to_celsius(fahrenheit):
return (fahrenheit - 32) * 5/9
temp_f = celsius_to_fahrenheit(25)
print(f"25°C = {temp_f}°F") # 25°C = 77.0°F
temp_c = fahrenheit_to_celsius(77)
print(f"77°F = {temp_c}°C") # 77°F = 25.0°C
🌍 Scope
Where does a variable “live”?
Local variables:
Created inside a function, they exist only there.
def test():
x = 10 # Local variable
print(x) # 10
test()
print(x) # ❌ NameError: x doesn't exist!
Global variables:
Created outside functions, accessible everywhere.
x = 10 # Global
def test():
print(x) # Reads the global
test() # 10
print(x) # 10
Modifying a global variable inside a function:
counter = 0 # Global
def increment():
global counter # Tell Python we're modifying the global!
counter += 1
increment()
print(counter) # 1
increment()
print(counter) # 2
⚠️ Gotcha:
x = 10
def change():
x = 20 # Creates a NEW local variable!
print(x) # 20
change()
print(x) # 10 (global unchanged!)
💡 Best practice — avoid global:
# ❌ With global:
score = 0
def add_points(points):
global score
score += points
# ✅ Without global (better!):
def add_points(current_score, points):
return current_score + points
score = 0
score = add_points(score, 10) # 10
score = add_points(score, 5) # 15
Parameters + return is better than global!
📚 Docstrings — Documenting Functions
A docstring describes what a function does.
def calculate_area(width, height):
"""
Calculate the area of a rectangle.
Parameters:
width (float): The rectangle's width
height (float): The rectangle's height
Returns:
float: The area of the rectangle
"""
return width * height
# View the documentation:
help(calculate_area)
Use triple quotes """ for docstrings!
🎮 Practical Example — A Game
Organizing a Guess the Number game with functions:
import random
def get_number_input(prompt, min_val, max_val):
"""Get a number from the user within a range."""
while True:
try:
number = int(input(prompt))
if min_val <= number <= max_val:
return number
else:
print(f"Number must be between {min_val} and {max_val}")
except ValueError:
print("Please enter a valid number!")
def generate_secret_number(min_val, max_val):
"""Generate a random number to guess."""
return random.randint(min_val, max_val)
def check_guess(guess, secret):
"""Check the guess and give a hint."""
if guess == secret:
return "correct"
elif guess < secret:
return "too_low"
else:
return "too_high"
def play_game():
"""Main game function."""
print("🎮 Game: Guess the Number")
min_num = 1
max_num = 100
max_attempts = 7
secret = generate_secret_number(min_num, max_num)
for attempt in range(1, max_attempts + 1):
print(f"\nAttempt {attempt}/{max_attempts}")
guess = get_number_input(f"Your number ({min_num}-{max_num}): ",
min_num, max_num)
result = check_guess(guess, secret)
if result == "correct":
print(f"🎉 You win! Guessed in {attempt} attempts!")
return
elif result == "too_low":
print("⬆️ My number is higher")
else:
print("⬇️ My number is lower")
print(f"\n😢 Game over! The number was: {secret}")
# Start the game:
play_game()
Advantages:
- Each function solves one task
- Code is readable and clear
- Easy to test each part
- Easy to add new features
💡 Best Practices
1. Function naming:
# ✅ Good names (verbs, describe the action):
def calculate_total(): ...
def send_email(): ...
def validate_password(): ...
def find_maximum(): ...
# ❌ Bad names:
def func1(): ... # Unclear what it does
def do_stuff(): ... # Too vague
def x(): ... # Meaningless
2. One function = one task:
# ❌ Function does too much:
def process_user():
validate_input()
save_to_database()
send_email()
update_statistics()
log_action()
# ✅ Split into multiple functions:
def validate_user_input(): ...
def save_user(): ...
def notify_user_by_email(): ...
3. Function size:
Ideal: 10–20 lines
Maximum: 30–50 lines
If more: Split into multiple functions!
4. Avoid side effects:
# ❌ Modifies global state:
count = 0
def add(x, y):
global count
count += 1 # Side effect!
return x + y
# ✅ Pure function (no side effects):
def add(x, y):
return x + y # Just computes, changes nothing
5. Prefer return over print:
# ❌ Only prints:
def calculate(a, b):
result = a + b
print(result)
# ✅ Returns the value:
def calculate(a, b):
return a + b
# Now the result can be used:
total = calculate(5, 3)
if total > 10:
print("Greater than 10")
⚠️ Common Mistakes
1. Forgot the colon:
# ❌ Error:
def greet()
print("Hi")
# ✅ Correct:
def greet():
print("Hi")
2. Forgot the indentation:
# ❌ Error:
def greet():
print("Hi")
# ✅ Correct:
def greet():
print("Hi")
3. Forgot to call it (missing parentheses):
def greet():
print("Hi")
greet # ❌ Prints nothing (this is the function object)
greet() # ✅ Hi
4. Confusing parameter and argument:
def greet(name): # name is a PARAMETER
print(f"Hi, {name}")
greet("Anna") # "Anna" is an ARGUMENT
5. Using a variable before it’s defined:
# ❌ Error:
def test():
print(x) # x not defined yet!
x = 10
# ✅ Correct:
def test():
x = 10
print(x)
🚀 Summary
Functions are the foundation of professional code!
You learned:
✅ Define functions with def
✅ Use parameters to pass data
✅ Return results with return
✅ Understand scope
✅ Organize code into reusable blocks
✅ Follow best practices
With functions you can:
- Avoid duplicating code
- Make code readable
- Simplify testing
- Scale your projects
- Work in a team more effectively
Practice in CodeHS! Create functions for everything:
- Calculators
- Validators
- Converters
- Games
Golden rule: If code repeats → create a function! 💪
Next step: Learn about lists and dictionaries to work with collections of data! 📦
💬 Comments (0)
No comments yet
Be the first to share your opinion about this article!