Skip to main content

Functions in Python

Functions in Python

Functions in Python are reusable blocks of code that perform a specific task. They allow you to break your code into smaller, manageable parts, make your code modular, and promote code reusability.

5.1 Defining a Function

In Python, a function is defined using the def keyword followed by the function name and parentheses (). You can also include parameters within the parentheses. Here's the basic structure of a Python function:

# Example of a simple function
def greet():
    print("Hello, welcome to Python!")

To call a function, simply write its name followed by parentheses:

# Calling a function
greet()

5.2 Function Arguments

Functions can take arguments (also called parameters) that allow you to pass data to the function.

# Function with arguments
def greet(name):
    print(f"Hello, {name}!")

# Calling the function with an argument
greet("Alice")

5.2.1 Positional Arguments

Arguments that are passed to a function in the correct positional order are called positional arguments.

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

# Calling the function with positional arguments
result = add_numbers(3, 5)
print(result)

5.2.2 Keyword Arguments

You can also pass arguments using the name of the parameter. These are called keyword arguments, and their order does not matter.

# Using keyword arguments
def greet_user(name, age):
    print(f"Name: {name}, Age: {age}")

greet_user(name="Alice", age=25)
greet_user(age=30, name="Bob")

5.2.3 Default Arguments

You can define default values for parameters in a function. If no argument is provided, the default value is used.

# Function with default arguments
def greet(name="Guest"):
    print(f"Hello, {name}!")

# Calling the function without an argument
greet()

# Calling the function with an argument
greet("Alice")

5.3 Return Values

Functions can return values using the return statement. This allows you to send a result back to the caller.

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

# Capture the return value in a variable
result = add_numbers(10, 5)
print(result)

5.4 Variable Scope

In Python, variables inside a function are called local variables, and they are only accessible within that function. Variables defined outside a function are global variables and can be accessed by any part of the program.

5.4.1 Local Variables

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

my_function()

# Trying to access local variable outside the function will cause an error
# print(x)  # Uncommenting this line will raise a NameError

5.4.2 Global Variables

# Global variable example
x = 5  # Global variable

def my_function():
    print(x)

my_function()
print(x)

5.4.3 Using global Keyword

If you want to modify a global variable inside a function, you can use the global keyword.

# Using the global keyword
x = 5

def my_function():
    global x
    x = 10  # Modifies the global variable

my_function()
print(x)  # Outputs 10

5.5 Lambda Functions

Lambda functions are small anonymous functions defined using the lambda keyword. They can have any number of arguments but only one expression. Lambda functions are often used for short, simple operations.

# Example of a lambda function
add = lambda a, b: a + b

# Using the lambda function
result = add(3, 5)
print(result)

5.6 Recursion

Recursion is a technique where a function calls itself. It's often used to solve problems that can be broken down into smaller, similar subproblems. Be careful when using recursion to ensure you include a base case to prevent infinite loops.

# Example of a recursive function
def factorial(n):
    if n == 1:
        return 1
    else:
        return n * factorial(n - 1)

# Calling the recursive function
print(factorial(5))  # Outputs 120

Comments

Popular posts from this blog

How to Add External Libraries (JAR files) in Eclipse

How to Add External Libraries (JAR files) in Eclipse Adding external libraries (JAR files) to your Eclipse project allows you to use third-party code in your application. This guide will explain what JAR files are, how they differ from `.java` files, where to download them, and how to add them to your project. What are JAR Files? JAR (Java ARchive) files are package files that aggregate many Java class files and associated metadata and resources (such as text, images, etc.) into a single file for distribution. They are used to distribute Java programs and libraries in a platform-independent format, making it easier to share and deploy Java applications. Difference between .java and .jar Files .java files are source files written in the Java programming language. They contain human-readable Java code that developers write. In contrast, .jar files are compile...

Managing Hierarchical Structures: OOP vs Nested Maps in Java

Managing Hierarchical Structures: OOP vs Nested Maps in Java This topic explores the pros and cons of managing hierarchical data using Object-Oriented Programming (OOP) versus nested map structures in Java. This discussion is contextualized with an example involving a chip with multiple cores and sub-cores. Nested Map of Maps Approach Using nested maps to manage hierarchical data can be complex and difficult to maintain. Here’s an example of managing a chip with cores and sub-cores using nested maps: Readability and Maintainability: Nested maps can be hard to read and maintain. The hierarchy is not as apparent as it would be with OOP. Encapsulation: The nested map approach lacks encapsulation, leading to less modular and cohesive code. Error-Prone: Manual management of keys and values increases the risk of errors, such as NullPointerExce...

Guide to Creating and Executing C Executables with Shared Libraries and Java Integration

Guide to Creating and Executing C Executables with Shared Libraries and Java Integration 1. Compiling a C Program to an Executable Step 1: Write a C Program #include <stdio.h> int main() { printf("Hello, World!\\n"); return 0; } Step 2: Compile the C Program gcc -o example example.c 2. Executing the C Program in the Console Step 3: Run the Executable ./example 3. Including Shared .so Libraries Step 4: Create a Shared Library #include <stdio.h> void my_function() { printf("Shared Library Function Called!\\n"); } gcc -shared -o libmylib.so -fPIC mylib.c Step 5: Update the C Program to Use the Shared Library #include <stdio.h> void my_function(); int main() { my_function(); printf("Hello, World!\\n...