Home HTML CSS JAVASCRIPT BOOTSTRAP Python Docker ML tutorial About us Privacy policy

Python Functions and Scope

Python Functions and Scope - CodesFamily

Python Functions and Scope

Functions in Python help break code into reusable blocks, making programs more organized and efficient.

Defining a Function


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

print(greet("Alice"))
        

Function Arguments


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

print(add(3, 5))  # Output: 8
        

Default Arguments


def power(base, exponent=2):
    return base ** exponent

print(power(4))  # Output: 16
print(power(4, 3))  # Output: 64
        

Variable Scope

Scope determines where variables can be accessed.

Global and Local Scope


global_var = "I am global"

def my_function():
    local_var = "I am local"
    print(local_var)

print(global_var)
my_function()
# print(local_var)  # This would cause an error
        

Using Global Variables Inside Functions


def modify_global():
    global global_var
    global_var = "Modified globally"

modify_global()
print(global_var)  # Output: Modified globally
        

Lambda Functions


square = lambda x: x * x
print(square(5))  # Output: 25
        

Returning Multiple Values


def get_user():
    return "Alice", 25

name, age = get_user()
print(name, age)  # Output: Alice 25
        

Conclusion

Functions are essential in Python for code reuse and maintainability. Understanding scope helps avoid unintended errors.