Page 1 of 1

Python: Scope

Posted: Tue Apr 07, 2026 5:31 pm
by Jason

Code: Select all

x = 2

	def example_function:

		x = 3

		print(f "The x variable inside the function is displaying {x}")

example_function()

print(f "The x variable outside the function is displaying {x}")

# The value change in the function doesn't affect the value of the variable outside and after the function.

Code: Select all

x = 5

print(f "The variable outside the function is {x}.")

	def function_using_global_keyword:

		global x = 6

		print(f "The variable inside the function is {x}.")

print(f "The variable outside the function after function displayed is {x}.")

# Due to the global keyword, the value

# change inside the function changes the value on the outside, so it has changed to 6, as it is in the function.