Coding Schools


 
Python | C Sharp | Azure AI | HTML | JavaScript | CSS | SQL Server
Python - Variable declarations
Conditional Statements in Python
Loops in Python
Python Functions
Python Classes
OOPS in Python
Python - Hello World Application
Python - import statements
Python - Web API

Python Functions



What is a Function?

A function is a block of reusable code designed to perform a single, related action. Functions help break your program into smaller, more manageable pieces and make the code more organized and readable.

Defining a Function

You define a function using the def keyword followed by the function name and parentheses () which may include parameters.

python
def function_name(parameters):
    """
    Optional: A docstring to describe the function.
    """
    # Code block
    return expression

Example of a Simple Function

Here' a simple example of a function that adds two numbers:

python
def add(a, b):
    return a + b

# Calling the function
result = add(3, 5)
print(result)  # Output: 8

Parameters and Arguments

Functions can accept parameters (inputs) and return a result (output). Parameters are specified within the parentheses in the function definition, while arguments are the actual values passed to the function when calling it.

Default Parameters

You can set default values for parameters. This makes them optional when calling the function:

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

greet()  # Output: Hello, Guest!
greet("Alice")  # Output: Hello, Alice!

Returning Values

A function can return a value using the return statement. Once the return statement is executed, the function terminates:

python
def multiply(a, b):
    return a * b

result = multiply(4, 5)
print(result)  # Output: 20

Functions with Multiple Parameters

You can define functions with multiple parameters:

python
def subtract(a, b):
    return a - b

result = subtract(10, 3)
print(result)  # Output: 7

Lambda Functions

Python also supports anonymous functions, known as lambda functions, which are defined using the lambda keyword. Lambda functions can have any number of arguments but only one expression:

python
# Lambda function to add two numbers
add = lambda x, y: x + y
print(add(3, 7))  # Output: 10

Scope and Lifetime of Variables

Variables declared inside a function are local to that function and cannot be accessed outside of it. This is known as the variable's scope:

python
def my_function():
    local_variable = 10
    print(local_variable)

my_function()  # Output: 10
# print(local_variable)  # This would cause an error because local_variable is not defined outside the function.

Using Functions for Modularity and Reusability

Functions allow you to modularize your code, making it reusable and easier to manage. By encapsulating tasks within functions, you can call the same function multiple times without rewriting the code.

Practical Example

Here' a practical example of a function that calculates the factorial of a number:

python
def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n-1)

# Calling the function
result = factorial(5)
print(result)  # Output: 120

In this example, the factorial function uses recursion to calculate the factorial of a number.

Python functions are a powerful tool that can help you write clean, efficient, and reusable code. If you have any more questions or need further examples, feel free to ask! Happy coding! ??




All rights reserved | Privacy Policy | Sitemap