Functions in Python

Functions are a way to encapsulate reusable logic in Python. They allow for modularity and make code easier to read and maintain.


What are Functions?

A function is a block of code designed to perform a specific task. Functions are executed only when they are called.

Syntax

def function_name(parameters):
    # Code block
    return result

Types of Functions

1. Built-in Functions

Python provides many built-in functions like print(), len(), and type().

2. User-defined Functions

Functions that you define yourself using the def keyword.

3. Anonymous Functions

These are functions created with the lambda keyword.


Defining a Function

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

To execute a function, call it by its name followed by parentheses, optionally passing arguments inside the parentheses.

Syntax

def function_name(parameters):
    # Code block
    return result

Example: Simple Function

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

greet()  # Output: Hello, World!

Python Function Arguments

Function arguments allow you to pass data into functions. There are several types of function arguments in Python:

Positional Arguments

The simplest form, where arguments are passed in the same order as the function parameters.

Example:

def greet(name, age):
    print(f"Hello {name}, you are {age} years old.")

greet("Alice", 25)  # Output: Hello Alice, you are 25 years old.

Keyword Arguments

You can pass arguments in the form key=value, which allows you to specify values by name, rather than position.

Example:

def greet(name, age):
    print(f"Hello {name}, you are {age} years old.")

greet(age=25, name="Bob")  # Output: Hello Bob, you are 25 years old.

Default Arguments

If an argument has a default value, it’s not mandatory to pass a value for that argument when calling the function.

Example:

def greet(name, age=30):
    print(f"Hello {name}, you are {age} years old.")

greet("Charlie")  # Output: Hello Charlie, you are 30 years old.

Variable-Length Arguments

These allow you to pass an arbitrary number of arguments to a function using *args for non-keyword arguments and **kwargs for keyword arguments.

Example:

def greet(*names):
    for name in names:
        print(f"Hello {name}")

greet("Alice", "Bob", "Charlie")

Output:

Hello Alice
Hello Bob
Hello Charlie
def greet(**details):
    for key, value in details.items():
        print(f"{key}: {value}")

greet(name="Alice", age=25)

Output:

name: Alice
age: 25

Return Statement

The return statement allows a function to send a result back to the caller.

Example

def square(num):
    return num ** 2

result = square(4)
print(result)  # Output: 16

Anonymous (Lambda) Functions

Lambda functions are concise, single-expression functions defined using the lambda keyword.

Lambda functions are small anonymous functions defined using the lambda keyword. They can have any number of arguments but only one expression.

Syntax

lambda arguments: expression

Example

square = lambda x: x**2
print(square(4))  # Output: 16

Scope and Lifetime of Variables

Variables defined inside a function are local to that function and cannot be accessed outside.

Example

def my_function():
    x = 10  # Local variable
    print(x)

my_function()  # Output: 10
print(x)       # Error: NameError

Docstrings

Use docstrings to document the purpose of a function. These are defined using triple quotes.

Example

def greet(name):
    """This function greets a person by their name."""
    print(f"Hello, {name}!")

greet("Alice")
print(greet.__doc__)  # Output: This function greets a person by their name.

Task

Practice: Functions in Python

Objective: Implement functions to solve problems and practice key concepts.

  1. Write a Function to Calculate Factorial: Write a function factorial(n) that calculates the factorial of a number recursively.

    def factorial(n):
        if n == 0:
            return 1
        return n * factorial(n-1)
    print(factorial(5))  # Output: 120
    
  2. Write a Function to Check Prime Numbers: Write a function is_prime(n) that returns True if a number is prime, otherwise False.

    def is_prime(n):
        if n <= 1:
            return False
        for i in range(2, int(n**0.5) + 1):
            if n % i == 0:
                return False
        return True
    print(is_prime(7))  # Output: True
    
  3. Create a Function with Default Parameters: Write a function greet_person(name="Friend") that prints a greeting.

    def greet_person(name="Friend"):
        print(f"Hello, {name}!")
    greet_person()          # Output: Hello, Friend!
    greet_person("Alice")  # Output: Hello, Alice!
    
  4. Write a Lambda Function: Create a lambda function that doubles a number and apply it to a list using map().

    double = lambda x: x * 2
    numbers = [1, 2, 3, 4]
    print(list(map(double, numbers)))  # Output: [2, 4, 6, 8]
    

Copyright © 2025 Devship. All rights reserved.

Made by imParth