Functions
A function is a reusable block of code that performs a specific task.
Defining a Function
def greet():
print("Hello!")
greet()
Output:
Hello!
Parameters
Parameters let you pass data into a function:
def greet(name):
print("Hello, " + name + "!")
greet("Alice")
greet("Bob")
Output:
Hello, Alice!
Hello, Bob!
Multiple Parameters
def greet(name, time_of_day):
print("Good " + time_of_day + ", " + name + "!")
greet("Alice", "morning")
Output:
Good morning, Alice!
Return Values
Use return to send a value back from a function:
def add(a, b):
return a + b
result = add(3, 5)
print(result)
Output:
8
Note: If a function has no return, it returns None.
Default Parameters
Give parameters default values:
def greet(name, greeting="Hello"):
print(greeting + ", " + name + "!")
greet("Alice")
greet("Bob", "Hi")
Output:
Hello, Alice!
Hi, Bob!
Scope
Variables inside a function are local—they only exist inside that function:
def calculate():
x = 10
return x * 2
result = calculate()
print(result) # 20
print(x) # Error! x doesn't exist here
Functions Calling Functions
Functions can call other functions:
def square(n):
return n * n
def sum_of_squares(a, b):
return square(a) + square(b)
print(sum_of_squares(3, 4))
Output:
25
Documenting Functions
Use a docstring to describe what a function does:
def calculate_area(width, height):
"""Calculate the area of a rectangle."""
return width * height
Practical Examples
Processing a list
def get_average(numbers):
total = 0
for num in numbers:
total = total + num
return total / len(numbers)
scores = [85, 90, 78, 92]
print(get_average(scores))
Output:
86.25
Validating input
def is_valid_age(age):
if age < 0:
return False
if age > 120:
return False
return True
print(is_valid_age(25)) # True
print(is_valid_age(-5)) # False
Formatting output
def format_name(first, last):
return last + ", " + first
print(format_name("Alice", "Smith"))
Output:
Smith, Alice
Common Mistakes
Forgetting to call the function
# Wrong - this just references the function
def greet():
print("Hello!")
greet # Nothing happens
# Right - use parentheses to call it
greet()
Forgetting to return a value
# Wrong - returns None
def add(a, b):
result = a + b
print(add(3, 5)) # None
# Right - return the result
def add(a, b):
return a + b
print(add(3, 5)) # 8
Printing instead of returning
# Wrong - can't use the result
def add(a, b):
print(a + b)
result = add(3, 5) # result is None
# Right - return so you can use it
def add(a, b):
return a + b
result = add(3, 5) # result is 8
Wrong number of arguments
def greet(name, age):
print(name + " is " + str(age))
# Wrong - missing argument
greet("Alice") # Error!
# Right - provide both arguments
greet("Alice", 20)
Indentation errors
# Wrong - code outside the function
def greet():
print("Hello!")
# Right - indent code inside the function
def greet():
print("Hello!")