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

Arrays, Lists, and LinkedLists in Java

Arrays, Lists, and LinkedLists in Java Understanding the differences between arrays, lists, and linked lists is fundamental in Java programming. Each data structure has its unique characteristics and use cases. This guide will delve into how these structures work, their advantages and disadvantages, and provide examples of how to use them in Java. 1. Arrays in Java An array is a fixed-size data structure that stores elements of the same type in contiguous memory locations. Arrays are one of the simplest and most commonly used data structures in Java. 1.1 Declaring and Initializing Arrays You can declare and initialize an array as follows: public class ArrayExample { public static void main(String[] args) { // Declaration and initialization int[] numbers = new int[5]; // Array of integers with size 5 numbers[0] = 10; numbers[1] = 20...

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...

Mastering Java Maps

In Java, maps are a versatile and powerful data structure that allow for the efficient storage and retrieval of key-value pairs. This document will cover various aspects of using maps in Java, from basic operations to advanced use cases. Overview of Maps Maps are part of the Java Collections Framework and provide a way to store data in key-value pairs. The keys are unique, and each key maps to exactly one value. Maps are crucial for tasks where quick lookups, insertions, and deletions are needed. Types of Maps Java provides several implementations of the Map interface, each with different characteristics: HashMap: Stores key-value pairs in a hash table. It does not guarantee any order of its elements. It allows one null key and multiple null values. LinkedHashMap: Extends HashMap and maintains a doubly-linked...