Python Functions Basics
Introduction
Functions are one of the most important building blocks in Python programming. They allow you to organize your code into reusable blocks, making your programs more modular, maintainable, and easier to understand. Think of functions as mini-programs within your main program that perform specific tasks.
In this tutorial, you'll learn:
- What functions are and why they're important
- How to define and call your own functions
- Working with parameters and return values
- Function scope basics
What Are Functions?
A function is a block of organized, reusable code that performs a specific task. Instead of writing the same code multiple times, you can create a function once and call it whenever you need that functionality.
Python has many built-in functions that you've likely already used, such as print()
, len()
, and input()
. These built-in functions make common tasks easier, but the real power comes when you create your own functions tailored to your specific needs.
Defining a Function
The basic syntax for defining a function in Python uses the def
keyword:
def function_name(parameters):
"""Docstring explaining what the function does"""
# Code block
# More code
return value # Optional
Let's break down the components:
def
keyword: Signals that you're defining a functionfunction_name
: A descriptive name for your function (follow variable naming rules)parameters
: Optional inputs that the function can acceptdocstring
: A comment describing what the function does (good practice)- Code block: The indented statements that run when the function is called
return
: Optional statement that exits the function and returns a value
Your First Function
Let's create a simple function that greets a user:
def greet():
"""Print a greeting message"""
print("Hello! Welcome to Python functions.")
To use this function, you need to call it:
greet() # Call the function
Output:
Hello! Welcome to Python functions.
This simple example demonstrates the basic structure, but functions become much more powerful when we add parameters and return values.
Function Parameters
Parameters allow you to pass information to functions. They act as variables inside the function:
def greet_person(name):
"""Greet a specific person"""
print(f"Hello, {name}! Nice to meet you.")
# Call the function with an argument
greet_person("Alex")
greet_person("Taylor")
Output:
Hello, Alex! Nice to meet you.
Hello, Taylor! Nice to meet you.
You can define multiple parameters by separating them with commas:
def describe_pet(animal_type, pet_name):
"""Display information about a pet"""
print(f"I have a {animal_type} named {pet_name}.")
describe_pet("dog", "Rex")
describe_pet("cat", "Whiskers")
Output:
I have a dog named Rex.
I have a cat named Whiskers.
Default Parameter Values
You can set default values for parameters, which are used when no argument is provided:
def greet_with_message(name, message="Good day"):
"""Greet a person with a custom or default message"""
print(f"{message}, {name}!")
greet_with_message("Jamie") # Uses default message
greet_with_message("Casey", "Welcome back") # Uses custom message
Output:
Good day, Jamie!
Welcome back, Casey!
Return Values
Functions can send back results using the return
statement:
def add_numbers(a, b):
"""Add two numbers and return the result"""
sum_result = a + b
return sum_result
# Store the returned value in a variable
result = add_numbers(5, 3)
print(f"The sum is: {result}")
# Use the returned value directly in an expression
print(f"Double the sum: {add_numbers(5, 3) * 2}")
Output:
The sum is: 8
Double the sum: 16
A function stops executing when it reaches a return
statement. You can have multiple return
statements in a function, but only one will execute based on conditions:
def get_absolute(number):
"""Return the absolute value of a number"""
if number >= 0:
return number
else:
return -number
print(get_absolute(5))
print(get_absolute(-7))
Output:
5
7
Function Scope
Variables defined inside a function have a local scope, meaning they can only be accessed within that function:
def calculate_area():
"""Calculate the area of a rectangle"""
length = 10
width = 5
area = length * width
print(f"Area inside function: {area}")
calculate_area()
# This would cause an error as 'area' is not defined outside the function
# print(f"Area outside function: {area}")
Output:
Area inside function: 50
Variables defined outside any function have a global scope and can be accessed inside functions:
message = "Hello, world!"
def display_message():
"""Display the global message"""
print(message)
display_message()
Output:
Hello, world!
Practical Examples
Example 1: Temperature Converter
def celsius_to_fahrenheit(celsius):
"""Convert Celsius to Fahrenheit"""
fahrenheit = (celsius * 9/5) + 32
return fahrenheit
def fahrenheit_to_celsius(fahrenheit):
"""Convert Fahrenheit to Celsius"""
celsius = (fahrenheit - 32) * 5/9
return celsius
# Test the functions
temp_c = 25
temp_f = celsius_to_fahrenheit(temp_c)
print(f"{temp_c}°C is equal to {temp_f:.1f}°F")
temp_f = 98.6
temp_c = fahrenheit_to_celsius(temp_f)
print(f"{temp_f}°F is equal to {temp_c:.1f}°C")
Output:
25°C is equal to 77.0°F
98.6°F is equal to 37.0°C
Example 2: Simple Calculator
def calculator(num1, num2, operation):
"""Perform basic arithmetic operations"""
if operation == "add":
return num1 + num2
elif operation == "subtract":
return num1 - num2
elif operation == "multiply":
return num1 * num2
elif operation == "divide":
if num2 != 0: # Avoid division by zero
return num1 / num2
else:
return "Error: Division by zero"
else:
return "Error: Unknown operation"
# Test the calculator
print(calculator(10, 5, "add")) # Addition
print(calculator(10, 5, "subtract")) # Subtraction
print(calculator(10, 5, "multiply")) # Multiplication
print(calculator(10, 5, "divide")) # Division
print(calculator(10, 0, "divide")) # Division by zero
Output:
15
5
50
2.0
Error: Division by zero
Example 3: Password Validator
def is_valid_password(password):
"""
Check if a password meets security criteria:
- At least 8 characters long
- Contains at least one digit
- Contains at least one uppercase letter
"""
if len(password) < 8:
return False
has_digit = False
has_uppercase = False
for char in password:
if char.isdigit():
has_digit = True
if char.isupper():
has_uppercase = True
return has_digit and has_uppercase
# Test passwords
passwords = ["abc123", "Password123", "hello", "SECUREPASS", "Secure123"]
for pwd in passwords:
if is_valid_password(pwd):
print(f"'{pwd}' is a valid password")
else:
print(f"'{pwd}' is NOT a valid password")
Output:
'abc123' is NOT a valid password
'Password123' is a valid password
'hello' is NOT a valid password
'SECUREPASS' is NOT a valid password
'Secure123' is a valid password
Summary
In this tutorial, you've learned:
- How to define functions using the
def
keyword - Working with function parameters and default values
- Returning values from functions
- Understanding variable scope in functions
- Applying functions to solve practical problems
Functions are a fundamental concept in programming that will help you write cleaner, more maintainable code. As you continue learning Python, you'll find that functions are essential for organizing your code as your programs become more complex.
Practice Exercises
- Create a function that takes a list of numbers and returns the average.
- Write a function that checks if a number is prime.
- Create a function that counts how many vowels are in a string.
- Write a function that takes a list of numbers and returns a new list with only the even numbers.
- Create a function that generates a random password of a specified length.
Additional Resources
Now that you understand the basics of Python functions, you're ready to create more modular and reusable code in your Python projects!
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)