Problem: you wrote a discount calculation — needed in 10 places, so you copy it 10 times. You find a bug — you fix it in 10 places.
Solution: a function is a named block of code that can be called as many times as needed.
Defining a Function
def function_name(parameters):
code
return result # optional
def— keyword- Colon
:is required - Function body — indented
def say_hello():
print("Hello!")
print("How are you?")
say_hello() # Hello! How are you?
say_hello() # can be called as many times as needed
Parameters and Arguments
A parameter is the name in the function definition. An argument is the value passed when calling.
One or multiple parameters
def greet(name):
print(f"Hello, {name}!")
greet("Anna") # Hello, Anna!
greet("Bob") # Hello, Bob!
def introduce(name, age, city):
print(f"{name}, {age} years old, from {city}")
introduce("Anna", 16, "Moscow") # Anna, 16 years old, from Moscow
Default parameter values
def greet(name="Guest"):
print(f"Hello, {name}!")
greet() # Hello, Guest!
greet("Anna") # Hello, Anna!
Keyword arguments
def create_profile(name, age, city):
print(f"{name}, {age}, {city}")
create_profile(age=16, city="Moscow", name="Anna") # order doesn't matter
Return: Giving Back a Value
# Without return — the function returns None
def add_print(a, b):
print(a + b)
result = add_print(5, 3) # prints 8
print(result) # None ❌
# With return — sends the value back for use
def add(a, b):
return a + b
result = add(5, 3) # result = 8 ✅
print(result) # 8
return also stops the function immediately:
def check_age(age):
if age < 18:
return "Minor" # exits here
return "Adult"
Returning multiple values
def get_stats(numbers):
return min(numbers), max(numbers), sum(numbers) / len(numbers)
low, high, avg = get_stats([4, 7, 2, 9, 1])
print(low, high, avg) # 1 9 4.6
Scope
Local variables — exist only inside the function:
def test():
x = 10
print(x) # 10
test()
print(x) # ❌ NameError: x doesn't exist!
Global variables — created outside functions, readable anywhere:
x = 10
def test():
print(x) # reads the global
test() # 10
To modify a global inside a function, use global:
counter = 0
def increment():
global counter
counter += 1
increment()
print(counter) # 1
It’s better to avoid global — pass values via parameters and return:
# ❌ With global
score = 0
def add_points(points):
global score
score += points
# ✅ Via parameters
def add_points(current_score, points):
return current_score + points
score = add_points(0, 10) # 10
score = add_points(score, 5) # 15
Practical Example: 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
return "Error: division by zero"
return "Unknown operation"
print(calculate(10, 5, "+")) # 15
print(calculate(10, 5, "/")) # 2.0
print(calculate(10, 0, "/")) # Error: division by zero
print(calculate(10, 5, "?")) # Unknown operation
Docstrings
Document your functions briefly with triple quotes:
def calculate_area(width, height):
"""Calculate the area of a rectangle. Returns float."""
return width * height
help(calculate_area) # display the documentation
Best Practices
1. Name functions with verbs:
# ✅ Good
def calculate_total(): ...
def validate_password(): ...
def send_email(): ...
# ❌ Bad
def func1(): ...
def x(): ...
2. One function = one task. If a function does 5 things, split it into 5 functions.
3. Use return instead of print — so the result can be used in code:
# ❌ Only prints, result cannot be reused
def calculate(a, b):
print(a + b)
# ✅ Returns the value
def calculate(a, b):
return a + b
total = calculate(5, 3)
if total > 10:
print("Greater than 10")
Common Mistakes
1. Forgot the colon or indentation:
def greet() # ❌ missing ':'
print("Hi") # ❌ missing indentation
def greet(): # ✅
print("Hi")
2. Forgot to call the function (missing parentheses):
greet # ❌ this is the function object, nothing runs
greet() # ✅
💬 Comments (0)
No comments yet
Be the first to share your opinion about this article!