6 of 20 topics completed
Python Functions
Functions are reusable blocks of code that perform specific tasks. They help organize code, reduce repetition, and make programs more maintainable.
Quick Overview
Function Basics
Define and call functions with parameters
Return Values
Get results back from functions
Arguments
Pass data to functions flexibly
Defining Functions
Functions are defined using the def
keyword, followed by the function name and parentheses. Parameters are optional and specified inside the parentheses.
1# Simple function with no parameters2def greet():3 print("Hello, World!")45# Function with parameters6def greet_person(name):7 print(f"Hello, {name}!")89# Function with multiple parameters10def calculate_rectangle_area(length, width):11 area = length * width12 return area1314# Call the functions15greet() # Output: Hello, World!16greet_person("Alice") # Output: Hello, Alice!17area = calculate_rectangle_area(5, 3) # Returns: 15
Return Values
Functions can return values using the return
statement. A function can return single values, multiple values, or nothing (returns None by default).
1# Return single value2def square(number):3 return number ** 245# Return multiple values6def get_coordinates():7 x = 108 y = 209 return x, y # Returns a tuple1011# Return conditional values12def get_grade(score):13 if score >= 90:14 return "A"15 elif score >= 80:16 return "B"17 else:18 return "C"1920# Using returned values21result = square(5) # Returns: 2522x_pos, y_pos = get_coordinates() # Unpacking returned tuple23grade = get_grade(85) # Returns: "B"
Function Arguments
Python provides different ways to pass arguments to functions, including default values, keyword arguments, and variable-length arguments.
1# Default parameter values2def greet(name, greeting="Hello"):3 print(f"{greeting}, {name}!")45# Keyword arguments6def create_profile(name, age, city):7 return f"{name} is {age} years old from {city}"89# Variable-length arguments10def calculate_sum(*numbers):11 return sum(numbers)1213# Variable-length keyword arguments14def print_info(**info):15 for key, value in info.items():16 print(f"{key}: {value}")1718# Using different argument types19greet("Alice") # Uses default greeting20greet("Bob", greeting="Hi") # Uses keyword argument21profile = create_profile(name="Charlie", age=25, city="London")22total = calculate_sum(1, 2, 3, 4, 5) # Sum any number of arguments23print_info(name="David", age=30, job="Developer")
🎯 Practice Exercise
Create these functions to practice what you've learned:
1# 1. Temperature Converter2# Create a function that converts Celsius to Fahrenheit3# Formula: (C × 9/5) + 32 = F45# 2. Password Validator6# Create a function that checks if a password is valid:7# - At least 8 characters long8# - Contains both uppercase and lowercase letters9# - Contains at least one number10# Return True if valid, False otherwise1112# 3. List Statistics13# Create a function that takes a list of numbers and returns:14# - The minimum value15# - The maximum value16# - The average value17# Return all three values as a tuple
Best Practices
Do's
- ✓ Use descriptive function names
- ✓ Keep functions focused on a single task
- ✓ Add docstrings for documentation
- ✓ Use type hints for clarity
Don'ts
- ✗ Write overly long functions
- ✗ Use global variables unnecessarily
- ✗ Repeat code across functions
- ✗ Mix different levels of abstraction
Related Tutorials
Learn object-oriented programming in Python.
Learn moreOrganize your code with modules and packages.
Learn moreEnhance functions with decorators.
Learn more