Connect with us

Hi, what are you looking for?

Programming

Scoping In Python

Scoping In Python
Scoping In Python

In this tutorial we going to look at scoping in python, we’ll start from 0 and finish scoping subjects. This tutorial consists of local scope, global scope, naming variables, and global keywords.

What Is Scoping?

We can also use a variable in a different environment than the one in which it was created. This is called scope. The best part of this is using your data regardless of where your data is created.

Local Scoping

If we have a function and there is a variable in it, if we use this variable only in this function, it becomes a local scope. As an example, there is a local scope example below.

def Function():
   a = 1
   print(a)

Function()

You can only use the variable “a” above in Function. For example, if you try to use variable and outside, it will give you an error. Such variables are called local scope variables.

def Function():
   a = 1
   def Function2():
      print(a)
   Function2()

Function()

Of course, you can use this variable in the auxiliary function inside the main function. Thus, you can create as many nested functions as you want and use your variables under different conditions.

Global Scope

Global variables can be used in every block. You need to write these variables to the python main body.

x = "Hello"
def Function():
   print(x)

Function()

As we talked about, global variables can be accessed from any structure and are valid for these nested functions.

x = "Hello"
def Function():
   print("x")
   def Function2():
      print(x)

Function()

Here we used a variable in the first function and used it in the second. we don’t necessarily need to use the variable in the first function.

Naming Variables

If you use two variables with the same variable name, you can use your variables both globally and locally, the local variable will be valid in the function except as a global variable.

x = "a"
def Function():
   x = "b"
   print(x)

print(x)
Function()
Global Keyword

With the global suffix, you can make a local variable global, so you can use a local variable globally.

def Function():
   global x

Function()
print(x)

CONGRATULATIONS, YOU FINISHED SCOPING IN PYTHON!

Click to comment

Leave a Reply

Your email address will not be published.

You May Also Like

News

According to a study from Dartmouth College, Dartmouth’s Tuck School of Business, and Indiana University, artificial intelligence systems can be trained to produce human-like...

Game Development

In this article, we are going to add the double jump feature for a simple 2D platform game. You can implement it in a...

Cyber Security

In this article, we are going to look at XSS attack types and how these attacks harm us. Also, we are going to learn...

Cyber Security

In this article, we are going to learn essential Bash commands. This article contains all of the essential topics about Bash scripting. We are...