Python Functions

Functions are blocks of reusable code designed to perform a specific task. They allow you to organize your program into logical sections, avoid repetition, and make code easier to maintain and understand.


Why Use Functions?

  • Reusability: Define once, use multiple times.
  • Organization: Group related code together.
  • Simplification: Break down complex problems into smaller parts.
  • Maintainability: Update logic in one place.

Defining a Function

To define a function in Python, use the def keyword followed by a name and parentheses.

def greet():
    print("Hello!")

This function doesn't take any input (called parameters) and simply prints a message.


Calling a Function

To execute the code inside a function, you must call it using its name followed by parentheses:

greet()

Output:

Hello!

Parameters and Arguments

Functions can take parameters to work with dynamic input.

def greet(name):
    print(f"Hello, {name}!")

Now you can pass a value when calling the function:

greet("Alice")

Output:

Hello, Alice!
  • Parameter: The variable in the function definition (name).
  • Argument: The actual value passed when calling the function ("Alice").

Multiple Parameters

You can define functions with multiple parameters:

def add(a, b):
    print(a + b)
add(5, 3)

Output:

8

Returning a Value

Instead of printing a result directly, functions can return values using the return keyword:

def multiply(a, b):
    return a * b
result = multiply(4, 2)
print(result)

Output:

8

Returning a value allows you to use it elsewhere in your code.


Default Parameter Values

You can provide default values for parameters. These are used if no argument is passed:

def greet(name="Guest"):
    print(f"Hello, {name}!")
greet()
greet("Bob")

Output:

Hello, Guest!
Hello, Bob!

Keyword Arguments

You can specify arguments by name:

def describe_pet(animal, name):
    print(f"{name} is a {animal}.")
describe_pet(name="Luna", animal="cat")

Output:

Luna is a cat.

Using keyword arguments improves readability.


Variable Number of Arguments

Sometimes you don’t know how many arguments you’ll need. Python provides two ways to handle this:

Arbitrary Positional Arguments

Use *args to accept multiple positional arguments as a tuple:

def total(*numbers):
    return sum(numbers)
print(total(1, 2, 3, 4))

Output:

10

Arbitrary Keyword Arguments

Use **kwargs to accept multiple keyword arguments as a dictionary:

def print_info(**info):
    for key, value in info.items():
        print(f"{key}: {value}")
print_info(name="Alice", age=30, job="Engineer")

Output:

name: Alice
age: 30
job: Engineer

Nested Functions

Functions can be defined inside other functions:

def outer():
    def inner():
        print("Inner function")
    inner()
outer()

Output:

Inner function

Nested functions can help encapsulate logic that’s only needed in a specific context.


Lambda Functions

A lambda function is a small anonymous function used for short, simple tasks:

square = lambda x: x ** 2
print(square(5))

Output:

25

Equivalent to:

def square(x):
    return x ** 2

Use lambda functions when you need a quick one-liner, especially with functions like map() or filter().


Summary

  • Use def to define functions.
  • Use return to output a value from a function.
  • Functions can take parameters and return values.
  • Use default values and keyword arguments for flexibility.
  • Handle variable numbers of arguments with *args and **kwargs.
  • Use lambda functions for simple one-line expressions.

Functions are the foundation of clean, reusable, and modular Python code. Mastering them will make your programs more organized, powerful, and maintainable.

Continue Learning

Python Variables

Popular

### Understanding Variables and Literals in Python Variables and literals are the foundation of any

Python Operators

For You

### Python Operators Operators in Python are special symbols or keywords used to perform operations

Python List

For You

### Python Lists: A Complete Introduction Lists are one of the most versatile and commonly used dat

Personalized Recommendations

Log in to get more relevant recommendations based on your reading history.