Python: Scope

Post Reply
User avatar
Jason
Site Admin
Posts: 767
Joined: Sun Dec 21, 2025 8:56 pm

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.
 

POSTREACT(ions) SUMMARY

Post Reply