DevAcademia
C++C#CPythonJava
  • Python Fundamentals

  • Introduction to Python
  • Getting Started with Python
  • Python Syntax
  • Python Comments
  • Python Variables
  • Python Data Types
  • Python Numbers
  • Python Casting
  • Python Strings
  • Python Booleans
  • Python Operators
  • Python Lists
  • Python Tuples
  • Python Sets
  • Python Dictionaries
  • Python If...Else
  • Python Match
  • Python While Loops
  • Python For Loops
  • Python Functions
  • Python Lambda
  • Python Arrays
  • Python OOP

  • Python OOP
  • Python Constructors
  • Python Destructors
  • Python Classes/Objects
  • Python Inheritance
  • Python Polymorphism
  • Python Quiz

  • Python Fundamentals Quiz
  • Python Fundamentals

  • Introduction to Python
  • Getting Started with Python
  • Python Syntax
  • Python Comments
  • Python Variables
  • Python Data Types
  • Python Numbers
  • Python Casting
  • Python Strings
  • Python Booleans
  • Python Operators
  • Python Lists
  • Python Tuples
  • Python Sets
  • Python Dictionaries
  • Python If...Else
  • Python Match
  • Python While Loops
  • Python For Loops
  • Python Functions
  • Python Lambda
  • Python Arrays
  • Python OOP

  • Python OOP
  • Python Constructors
  • Python Destructors
  • Python Classes/Objects
  • Python Inheritance
  • Python Polymorphism
  • Python Quiz

  • Python Fundamentals Quiz

Loading Python tutorial…

Loading content
Python FundamentalsTopic 68 of 77
←PreviousPrevNextNext→

Python Functions

Function Basics

Functions are reusable blocks of code that perform a specific task. They help organize code, avoid repetition, and make programs easier to maintain and understand.

Example
# Defining and calling functions
def greet(name):
    """This function greets the person passed as parameter."""
    return f"Hello, {name}!"

# Function call
message = greet("Alice")
print(message)

# Function with multiple parameters
def add_numbers(a, b):
    return a + b

result = add_numbers(5, 3)
print(f"5 + 3 = {result}")
Output
Hello, Alice!
5 + 3 = 8

Function Arguments

Python functions support different types of arguments: positional, keyword, default, and variable-length.

Example
# Different types of arguments
def describe_person(name, age, city="Unknown"):
    """Function with required and default parameters."""
    print(f"Name: {name}, Age: {age}, City: {city}")

# Positional arguments
describe_person("Alice", 25, "New York")

# Keyword arguments
describe_person(age=30, name="Bob", city="London")

# Default parameter
describe_person("Charlie", 35)

# Variable-length arguments
def print_items(*items):
    """Function that accepts any number of arguments."""
    for item in items:
        print(item)

print_items("apple", "banana", "cherry")
Output
Name: Alice, Age: 25, City: New York
Name: Bob, Age: 30, City: London
Name: Charlie, Age: 35, City: Unknown
apple
banana
cherry

Return Values and Scope

Functions can return values using the `return` statement. Variables declared inside functions have local scope and are not accessible outside.

Example
# Return values and scope
def calculate_stats(numbers):
    """Calculate statistics for a list of numbers."""
    total = sum(numbers)
    count = len(numbers)
    average = total / count if count > 0 else 0
    
    # Return multiple values as a tuple
    return total, count, average

# Unpack returned values
numbers = [10, 20, 30, 40, 50]
total, count, average = calculate_stats(numbers)
print(f"Total: {total}, Count: {count}, Average: {average}")

# Scope example
def test_scope():
    local_var = "I'm local"
    print(local_var)

test_scope()
# print(local_var)  # Would raise NameError: not defined outside the function
Output
Total: 150, Count: 5, Average: 30.0
I'm local

Recursive Functions

A function can call itself, which is called recursion. This is useful for problems that can be defined in terms of smaller subproblems.

Example
# Recursive function for factorial
def factorial(n):
    """Calculate factorial using recursion."""
    if n == 0 or n == 1:
        return 1
    return n * factorial(n - 1)

print(f"Factorial of 5: {factorial(5)}")

# Recursive function for Fibonacci numbers
def fibonacci(n):
    """Return the nth Fibonacci number using recursion."""
    if n <= 1:
        return n
    return fibonacci(n - 1) + fibonacci(n - 2)

print("Fibonacci sequence:")
for i in range(8):
    print(fibonacci(i), end=" ")
Output
Factorial of 5: 120
Fibonacci sequence:
0 1 1 2 3 5 8 13 
Test your knowledge: Python Functions
Quiz Configuration
4 of 8 questions
Sequential
Previous allowed
Review enabled
Early close allowed
Estimated time: 5 min
Python FundamentalsTopic 68 of 77
←PreviousPrevNextNext→