Behavior of value of the global variable in different situations in Python

Serdar A.
2 min readFeb 9, 2025

--

Hi everyone

In python value of the global variable can be change or not change in different situations ( like inside/outside function, if conditions, loops)

  • Let’s try with function
value = 4

def fonk1(value):
print("inside func before change : ",value)
value = 5
print("inside func after change : ",value)

print("value before function call ",value)
fonk1(value)
print("value after function call ",value)

Output is :

value before function call  4
inside func before change : 4
inside func after change 5
value after function call 4

global value changes inside function but it remain same value in outside.

  • Let’s try with list object
list1 = [1,2,3,4]

def fonk2(list1):
print("before change inside function : ",list1)
list1 = [100,200,300]
print("after change inside function : ", list1)
print(list1)

print("list before call function : ",list1)
fonk2(list1)
print("list after called function : ", list1)

Output is :

list before call function :  [1, 2, 3, 4]
before change inside function : [1, 2, 3, 4]
after change inside function : [100, 200, 300]
[100, 200, 300]
list after called function : [1, 2, 3, 4]
  • Let’s look at changing value situations
value = 4

def fonk1(variable):
global value // global keyword
value = variable
print("inside function after change value : ",value)

print("value before function call : ",value)
fonk1(8)
print("value after function call : ",value)

Output is :

value before function call :  4
inside function after change value : 8
value after function call : 8

global value changed. With the statement global value, you’re telling Python to look in the global scope for the name value.

  • Let’s try with if block
value = 1

if value < 10:
value = 5

print("value : ", value)

Output is :

value :  5

A variable which in if block act as global variable.

  • Let’s try with loop block
value = 1
list1 = [1,2,3,4,5]

for i in list1:
value +=1

print("value : ", value)

Output is :

value :  6

A variable which in loop block act as global variable.

I hope, it was useful for you.

--

--

Serdar A.
Serdar A.

Written by Serdar A.

Senior Software Developer & Architect at Havelsan Github: https://github.com/serdaralkancode #Java & #Spring & #BigData & #React & #Microservice

No responses yet