Progress0%

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.

Python
1# Simple function with no parameters
2def greet():
3 print("Hello, World!")
4
5# Function with parameters
6def greet_person(name):
7 print(f"Hello, {name}!")
8
9# Function with multiple parameters
10def calculate_rectangle_area(length, width):
11 area = length * width
12 return area
13
14# Call the functions
15greet() # 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).

Python
1# Return single value
2def square(number):
3 return number ** 2
4
5# Return multiple values
6def get_coordinates():
7 x = 10
8 y = 20
9 return x, y # Returns a tuple
10
11# Return conditional values
12def get_grade(score):
13 if score >= 90:
14 return "A"
15 elif score >= 80:
16 return "B"
17 else:
18 return "C"
19
20# Using returned values
21result = square(5) # Returns: 25
22x_pos, y_pos = get_coordinates() # Unpacking returned tuple
23grade = 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.

Python
1# Default parameter values
2def greet(name, greeting="Hello"):
3 print(f"{greeting}, {name}!")
4
5# Keyword arguments
6def create_profile(name, age, city):
7 return f"{name} is {age} years old from {city}"
8
9# Variable-length arguments
10def calculate_sum(*numbers):
11 return sum(numbers)
12
13# Variable-length keyword arguments
14def print_info(**info):
15 for key, value in info.items():
16 print(f"{key}: {value}")
17
18# Using different argument types
19greet("Alice") # Uses default greeting
20greet("Bob", greeting="Hi") # Uses keyword argument
21profile = create_profile(name="Charlie", age=25, city="London")
22total = calculate_sum(1, 2, 3, 4, 5) # Sum any number of arguments
23print_info(name="David", age=30, job="Developer")

🎯 Practice Exercise

Create these functions to practice what you've learned:

Python
1# 1. Temperature Converter
2# Create a function that converts Celsius to Fahrenheit
3# Formula: (C × 9/5) + 32 = F
4
5# 2. Password Validator
6# Create a function that checks if a password is valid:
7# - At least 8 characters long
8# - Contains both uppercase and lowercase letters
9# - Contains at least one number
10# Return True if valid, False otherwise
11
12# 3. List Statistics
13# Create a function that takes a list of numbers and returns:
14# - The minimum value
15# - The maximum value
16# - The average value
17# 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 more

Organize your code with modules and packages.

Learn more

Enhance functions with decorators.

Learn more