image
image
image

Python’s Global and Local Variable

image

The following example shows how to use both local and global variables in the same Python program

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

y = "global"

def foo():

global y

x = "local"

y = y * 2

print(y)

print(x)

foo()

Discussion

The output of the program will be:

global global

local

Discussion

We declared y as a global variable and x as a local variable in the foo(). The * operator issued to modify the global variable y and finally, we printed both y and x.

Local and Global Variables with the same name

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

y=6

def foo():

y=11

print(“Local variable y-“, y)

foo()

print("Global variable y-", y)