No Widget Added

Please add some widget in Offcanvs Sidebar

Shopping cart

shape
shape

Python Variable Types

Python variable

There are two types of variables in Python – Local variable and Global variable.

Local Variable

A local variable is a variable that is defined within a function and is only accessible within that function’s scope. Local variables are created when the function starts execution and are destroyed when the function ends. They are not accessible outside the function in which they are defined.

Characteristics of Local Variables

  • Scope: Local to the function.
  • Lifetime: Exist only during the execution of the function.
  • Visibility: Not accessible outside the function.

Example of Local Variables

def my_function():
    x = 10  # x is a local variable
    y = 20  # y is a local variable
    print(f"x: {x}, y: {y}")

my_function()
# Output: x: 10, y: 20

# Trying to access x or y outside the function will raise an error
print(x)  # NameError: name 'x' is not defined

Global Variables

Global variables in Python are variables that are defined outside of any function or class, and thus they can be accessed and modified throughout the entire program, including inside functions and classes.

Characteristics of Global Variables

  • Scope: Global scope, accessible throughout the entire program.
  • Lifetime: Exist for the duration of the program’s execution.
  • Visibility: Can be accessed from any part of the program, including inside functions and classes.

Example of Global Variables

x = 10  # global variable

def print_x():
    print(f"x: {x}")

print_x()  # Output: x: 10

print(f"Outside function, x: {x}")  # Output: Outside function, x: 10

In this example, x is a global variable, and it can be accessed both inside the print_x function and outside of it.

Modifying Global Variables Inside Functions

To modify a global variable inside a function, you need to use the global keyword. This tells Python that you are referring to the global variable, not a local one.

Example of Modifying Global Variables

x = 5  # global variable

def modify_x():
    global x
    x = 10  # modify global variable
    print(f"Inside function, x: {x}")

modify_x()
# Output: Inside function, x: 10

print(f"Outside function, x: {x}")
# Output: Outside function, x: 10

By using the global keyword, the function can modify the global variable x.

Leave A Comment

Your email address will not be published. Required fields are marked *