Scopes in Python

What is scope in Python? How to use Scope in Python? Let's learn everything you need to know about Scope in Python with TipsMake.com.com!

What is scope in Python ? How to use Scope in Python ? Let's learn everything you need to know about Scope in Python with TipsMake !

Picture 1 of Scopes in Python

A variable is only available within the area it is created in. That is scope in Python. Scope or range in Python has two types:

  1. Local Scope
  2. Global Scope

Local Scope

A variable created inside a function belongs to that function's local scope in Python. And it can only be used inside that function.

For example:

A variable created inside a function is available within that function:

def myfunc(): x = 300 print(x) myfunc()

Functions within functions

As explained in the above example, the variable xis not available outside this function, but it is available to any function inside that function. For example:

Local variables can be accessed from a function inside this function:

def myfunc(): x = 300 def myinnerfunc(): print(x) myinnerfunc() myfunc()

Global Scope

A variable created in the main body of Python code is a global variable and belongs to the global scope.

Global variables are available in any scope, both global and local.

For example:

A variable created outside a function is local and can be used by anyone:

x = 300 def myfunc(): print(x) myfunc() print(x)

Name the variable

If you operate on the same variable name inside and outside of a function, Python will treat them as two separate variables. One is available in the global scope (outside of the function), and one is available in the local scope (inside the function).

For example: The function below will 'print' local scope x , then this code will print global scope x :

x = 300 def myfunc(): x = 200 print(x) myfunc() print(x)

Global keyword

If you need to create a local variable, but are 'stuck' in the local scope, you can use the global- global keyword. Keywords globalcreate global variables.

For example: If you use the keyword global, the variable belongs to the global scope:

def myfunc(): global x x = 300 myfunc() print(x)

Also, use the keyword globalif you want to make changes to a global variable inside a function.

Example: To change the value of a global variable inside a function, refer to the variable using the keyword global:

x = 300 def myfunc(): global x x = 200 myfunc() print(x)

Above are the basic things you need to know about scope in Python . Hope this article helps you better understand scope when programming in Python .

Update 17 October 2023
Category

System

Mac OS X

Hardware

Game

Tech info

Technology

Science

Life

Application

Electric

Program

Mobile