Python - Variables

5.
Differentiate between local and global variables in Python.

Local Variables:

# Local variables are defined within a specific function or block
def my_function():
    local_variable = 10
    print("Inside function:", local_variable)

# Calling the function to demonstrate the local variable
my_function()

# Attempting to access local_variable here would result in an error

In the above example, the variable local_variable is defined within the function my_function(). It is accessible only within the scope of that function. Once the function execution is complete, the local variable is destroyed, and attempting to access it outside the function would result in an error.

Global Variables:

# Global variables are defined outside of any function or block, 
# making them accessible throughout the program
global_variable = 20

# Function accessing the global variable
def my_function():
    print("Inside function:", global_variable)

# Calling the function to demonstrate the global variable
my_function()

# Global variables are also accessible outside functions
print("Outside function:", global_variable)

In the second example, the variable global_variable is defined outside any function or block, making it a global variable. It is accessible throughout the entire program, both within and outside functions. The value of the global variable persists for the entire duration of the program.

These examples illustrate the differences in scope and lifetime between local and global variables in Python.


6.
Explain the concept of variable scope in Python.

Variable scope in Python refers to the region of the code where a variable is accessible or can be modified. In Python, there are two main types of variable scope: local and global.

Local scope refers to the portion of code where a variable is declared within a function or block. Local variables are only accessible within that specific function or block and are not visible outside of it.

Global scope refers to the portion of code where a variable is declared outside of any function or block. Global variables are accessible from any part of the code, both inside and outside functions.

# Global variable
global_variable = 10

def example_function():
    # Local variable
    local_variable = 5
    
    # Accessing global variable within the function
    global_variable_inside_function = global_variable + 2
    
    # Printing local and modified global variables
    print("Local variable inside function:", local_variable)
    print("Modified global variable inside function:", global_variable_inside_function)

# Call the function
example_function()

# Attempting to access local variable outside the function (will result in an error)
# print("Attempt to access local variable outside function:", local_variable)

In Python, nested scope occurs when a variable is declared within an inner block or function, making it accessible within that block as well as any nested blocks or functions:

# Global variable
global_variable = 10

def outer_function():
    # Outer function's local variable
    outer_variable = 5
    
    def inner_function():
        # Inner function's local variable
        inner_variable = 3
        
        # Accessing variables from outer scopes
        total_sum = outer_variable + inner_variable + global_variable
        
        # Printing variables
        print("Total sum inside inner function:", total_sum)

    # Call the inner function
    inner_function()

# Call the outer function
outer_function()

7.
What are the built-in types for variables in Python?

In Python, there are several built-in data types that represent the different kinds of values variables can take. These built-in types include:

  • int: Integer type, representing whole numbers.

  • float: Floating-point type, representing decimal numbers.

  • str: String type, representing text.

  • bool: Boolean type, representing True or False values.

  • list: List type, representing ordered, mutable sequences of elements.

  • tuple: Tuple type, representing ordered, immutable sequences of elements.

  • set: Set type, representing an unordered collection of unique elements.

  • dict: Dictionary type, representing a collection of key-value pairs.

Here's an example program demonstrating the use of these built-in types:

# Integer type
my_integer = 42

# Floating-point type
my_float = 3.14

# String type
my_string = "Hello, Python!"

# Boolean type
is_true = True

# List type
my_list = [1, 2, 3, 4, 5]

# Tuple type
my_tuple = (10, 20, 30)

# Set type
my_set = {1, 2, 3, 4, 5}

# Dictionary type
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}

# Printing variables
print("Integer:", my_integer)
print("Float:", my_float)
print("String:", my_string)
print("Boolean:", is_true)
print("List:", my_list)
print("Tuple:", my_tuple)
print("Set:", my_set)
print("Dictionary:", my_dict)

The output of the provided example program would be:

Integer: 42
Float: 3.14
String: Hello, Python!
Boolean: True
List: [1, 2, 3, 4, 5]
Tuple: (10, 20, 30)
Set: {1, 2, 3, 4, 5}
Dictionary: {'name': 'John', 'age': 25, 'city': 'New York'}

8.
How do you swap the values of two variables in Python without using a temporary variable?

Here's a Python code snippet that swaps the values of two variables without using a temporary variable:

# Swapping variables without using a temporary variable
def swap_without_temp(a, b):
    a = a + b
    b = a - b
    a = a - b
    return a, b

# Example usage
x = 5
y = 10

x, y = swap_without_temp(x, y)

print("After swapping: x =", x, ", y =", y)

In this code, the values of a and b are swapped without using a temporary variable. The swap is achieved using arithmetic operations.

Here's an alternative Python code snippet that swaps the values of two variables without using a temporary variable:

# Swapping variables without using a temporary variable
def swap_without_temp(a, b):
    a, b = b, a
    return a, b

# Example usage
x = 5
y = 10

x, y = swap_without_temp(x, y)

print("After swapping: x =", x, ", y =", y)

In this code, the values of a and b are swapped using a tuple unpacking assignment. This provides a concise and readable way to swap values in Python.