← View series: python tutorials
~/blog
Functions - Basics
Introduction
In this tutorial, you'll learn about functions - reusable blocks of code that perform specific tasks. Functions are fundamental to writing clean, organized, and maintainable programs. They'll help you avoid repeating code and make your programs more modular.
What You'll Learn
- What functions are and why to use them
- Defining and calling functions
- Parameters and arguments
- Return values
- Variable scope (local vs global)
- Default parameter values
What are Functions?
Functions are reusable blocks of code that perform a specific task. Instead of writing the same code multiple times, you can define it once and call it whenever needed.
Why Use Functions?
| Benefit | Description |
|---|---|
| Reusability | Write once, use many times |
| Modularity | Break code into manageable pieces |
| Readability | Code is easier to understand |
| Maintainability | Changes needed in only one place |
| Testing | Easier to test individual pieces |
Defining Functions
Basic Function
# Define a function using 'def'
def greet():
print("Hello, World!")
# Call the function
greet()Output:
Hello, World!
Function with Parameters
# Function with a parameter
def greet(name):
print(f"Hello, {name}!")
greet("Alice") # Hello, Alice!
greet("Bob") # Hello, Bob!Multiple Parameters
def greet_person(first_name, last_name):
print(f"Hello, {first_name} {last_name}!")
greet_person("John", "Doe") # Hello, John Doe!Return Values
Functions can return values using the return statement:
# Function that returns a value
def add(a, b):
return a + b
result = add(5, 3)
print(result) # 8
# Can also use directly
print(add(10, 20)) # 30Returning Multiple Values
Python functions can return multiple values (as a tuple):
def get_stats(numbers):
total = sum(numbers)
average = total / len(numbers)
return total, average
# Unpack the returned tuple
total, average = get_stats([10, 20, 30])
print(f"Total: {total}, Average: {average}")
# Total: 60, Average: 20.0Early Return
Use return to exit a function early:
def find_first_even(numbers):
for num in numbers:
if num % 2 == 0:
return num # Exit immediately when found
return None # No even number found
print(find_first_even([1, 3, 5, 6, 7])) # 6
print(find_first_even([1, 3, 5, 7, 9])) # NoneDefault Parameters
You can provide default values for parameters:
# Function with default parameter
def greet(name="World"):
print(f"Hello, {name}!")
greet() # Hello, World!
greet("Alice") # Hello, Alice!
# Multiple defaults
def power(base, exponent=2):
return base ** exponent
print(power(3)) # 9 (3^2)
print(power(3, 3)) # 27 (3^3)⚠️ Important: Default parameters must come after non-default parameters
# Correct
def func(a, b=10, c=20):
pass
# Incorrect - will cause an error
# def func(a=10, b, c=20):
# passKeyword Arguments
You can specify arguments by name:
def introduce(name, age, city):
print(f"I'm {name}, {age} years old, from {city}")
# Positional arguments
introduce("Alice", 25, "NYC")
# Keyword arguments
introduce(name="Bob", age=30, city="LA")
# Mix of both (positional first, then keyword)
introduce("Charlie", city="Boston", age=35)Variable Scope
Variables created inside functions are local to that function:
# Local variable
def my_function():
x = 10 # Local variable
print(x)
my_function() # 10
# print(x) # Error! x is not defined outside
# Global variable
y = 20 # Global variable
def another_function():
print(y) # Can access global
another_function() # 20Using global Keyword
counter = 0
def increment():
global counter
counter += 1
print(counter)
increment() # 1
increment() # 2
increment() # 3
print(counter) # 3⚠️ Warning: Using global variables is generally discouraged. Pass values as parameters instead.
Practical Examples
Example 1: Temperature Converter
def celsius_to_fahrenheit(celsius):
return (celsius * 9/5) + 32
def fahrenheit_to_celsius(fahrenheit):
return (fahrenheit - 32) * 5/9
# Convert 0°C to Fahrenheit
print(celsius_to_fahrenheit(0)) # 32.0
# Convert 100°F to Celsius
print(fahrenheit_to_celsius(100)) # 37.777...Example 2: Password Validator
def is_valid_password(password):
# Check length
if len(password) < 8:
return False
# Check for uppercase
has_upper = any(c.isupper() for c in password)
# Check for lowercase
has_lower = any(c.islower() for c in password)
# Check for digit
has_digit = any(c.isdigit() for c in password)
return has_upper and has_lower and has_digit
# Test
print(is_valid_password("abc")) # False (too short)
print(is_valid_password("abcdefgh")) # False (no uppercase, no digit)
print(is_valid_password("Abcd1234")) # TrueExample 3: Fibonacci
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n-1) + fibonacci(n-2)
# Print first 10 Fibonacci numbers
for i in range(10):
print(fibonacci(i), end=" ")
# Output: 0 1 1 2 3 5 8 13 21 34Docstrings
Document your functions using docstrings:
def calculate_area(length, width):
"""
Calculate the area of a rectangle.
Args:
length: The length of the rectangle
width: The width of the rectangle
Returns:
The area (length * width)
"""
return length * width
# Access docstring
print(calculate_area.__doc__)Summary
In this tutorial, you learned:
- ✅ What functions are and why to use them
- ✅ Defining and calling functions
- ✅ Parameters and arguments
- ✅ Return values (including multiple values)
- ✅ Default parameter values
- ✅ Keyword arguments
- ✅ Variable scope (local vs global)
- ✅ Docstrings for documentation
🧑💻 Practice Exercise
Create a calculator program with functions for:
add(a, b)- returns sumsubtract(a, b)- returns differencemultiply(a, b)- returns productdivide(a, b)- returns quotient (handle division by zero)- A main function that takes two numbers and an operation, then calls the appropriate function
Click to see solution
# Calculator functions
def add(a, b):
"""Returns the sum of a and b"""
return a + b
def subtract(a, b):
"""Returns the difference of a and b"""
return a - b
def multiply(a, b):
"""Returns the product of a and b"""
return a * b
def divide(a, b):
"""Returns the quotient of a and b"""
if b == 0:
return "Error: Cannot divide by zero!"
return a / b
def calculator(a, b, operation):
"""Main calculator function"""
if operation == "+":
return add(a, b)
elif operation == "-":
return subtract(a, b)
elif operation == "*":
return multiply(a, b)
elif operation == "/":
return divide(a, b)
else:
return "Error: Invalid operation!"
# Test the calculator
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
op = input("Enter operation (+, -, *, /): ")
result = calculator(num1, num2, op)
print(f"Result: {result}")Sample Output:
Enter first number: 10
Enter second number: 5
Enter operation (+, -, *, /): *
Result: 50.0
What's Next
In the next tutorial, we'll learn about Functions - Advanced - covering lambda functions, *args, **kwargs, and decorators.