Python Global keyword Example wpaccuracy

please click here for more wordpress cource

Sure! In Python, the global keyword is used inside a function to indicate that a variable is a global variable, rather than a local variable. This means that the variable can be accessed and modified both inside and outside of the function.

Here’s an example:

count = 0

def increment_count():
    global count
    count += 1

increment_count()
print(count)   # Output: 1

In this example, we define a global variable count with an initial value of 0. We then define a function called increment_count that uses the global keyword to indicate that it wants to modify the global variable count. Inside the function, we simply add 1 to count.

When we call the increment_count function, it modifies the value of the global variable count by incrementing it by 1. We then print out the value of count, which is now 1.

Without the global keyword, the function would create a new local variable count, which would not affect the global variable with the same name:

count = 0

def increment_count():
    count = 1   # This creates a new local variable 'count'
    count += 1

increment_count()
print(count)   # Output: 0 (the global variable is not modified)

In this example, the count variable inside the increment_count function is a local variable that is completely separate from the global variable with the same name. Therefore, modifying the local variable does not affect the global variable, and the value of count remains 0.

You may also like...

Popular Posts

Leave a Reply

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