if a python function attempts to assign a value to a variable that is in global scope, what happens?
Python Variable Consignment
Explaining One Of The Most Key Concepts Of Python Programming Language
This article aims to explain how Python variable consignment works.
The Basics: Variables — Object Types And Scope
- Variables store data that can be used and/or changed in your programme. This information tin can be an integer, text, collection, etc.
- Variables are used to hold user inputs, local states of your program, etc.
- Variables have a name so that they tin can be referenced in the code.
- The fundamental concept to understand is that everything is an object in Python.
Python supports numbers, strings, sets, lists, tuples, and dictionaries. These are the standard data types. I will explain each of them in particular.
Declare And Assign Value To Variable
Assignment sets a value to a variable.
To assign variable a value, use the equals sign (=)
myFirstVariable = 1
mySecondVariable = 2
myFirstVariable = "Hello You" - Assigning a value is known as binding in Python. In the example above, nosotros take assigned the value of 2 to mySecondVariable.
Note how I assigned an integer value of 1 and so a cord value of "Hello You" to the same myFirstVariable variable. This is possible due to the fact that the data types are dynamically typed in python.
This is why Python is known as a dynamically typed programming language.
If you want to assign the same value to more than one variable then you can use the chained assignment:
myFirstVariable = mySecondVariable = 1 Numeric
- Integers, decimals, floats are supported.
value = 1 #integer
value = 1.2 #bladder with a floating point - Longs are also supported. They have a suffix of L e.g. 9999999999999L
Strings
- Textual information. Strings are a sequence of letters.
- A string is an array of characters
- A cord value is enclosed in quotation marks: single, double or triple quotes.
proper name = 'farhad'
name = "farhad"
proper noun = """farhad""" - Strings are immutable. Once they are created, they cannot be inverse e.g.
a = 'me' Updating it will neglect:
a[i]='y' It volition throw a Type Error
- When variables are assigned a new value then internally, Python creates a new object to store the value.
Therefore a reference/pointer to an object is created. This pointer is and so assigned to the variable and equally a result, the variable tin can be used in the program.
We tin can as well assign one variable to another variable. All it does is that a new arrow is created which points to the same object:
a = 1 #new object is created and 1 is stored in that location, new pointer is created, the pointer connects a to 1
b = a #new object is not created, new pointer is created only that connects b to i Variables can have local or global scope.
Local Scope
- Variables declared inside a role, every bit an example, can only exist within the block.
- In one case the cake exists, the variables also become inaccessible.
def some_funcion():
TestMode = Faux impress(TestMode) <- Breaks as the variable doesn't exist exterior
In Python, if-else and for/while loop block doesn't create any local scope.
for i in range(1, 11):
test_scope = "variable inside for loop" print(test_scope)
Output:
variable inside for loop With if-else cake
is_python_awesome = Truthful if is_python_awesome:
test_scope = "Python is awesome" print(test_scope)
Output:
Python is awesome Global Scope
- Variables that can be accessed from any office accept a global scope. They exist in the __main__ frame.
- You can declare a global variable exterior of functions. It's of import to notation that to assign a global variable a new value, you will accept to apply the "global" keyword:
TestMode = True
def some_function():
global TestMode
TestMode = False some_function()
print(TestMode) <--Returns False
Removing the line "global TestMode" will just gear up the variable to False within the some_function() function.
Notation: Although I volition write more than on the concept of modules later, but if you want to share a global variable across a number of modules then you can create a shared module file e.grand. configuration.py and locate your variable in that location. Finally, import the shared module in your consumer modules.
Finding Variable Blazon
- If you want to find the type of a variable, you lot tin implement:
type('farhad')
--> Returns <blazon 'str'> Comma In Integer Variables
- Commas are treated as a sequence of variables e.thousand.
9,viii,7 are three numeric variables 3. Operations
- Allows u.s.a. to perform ciphering on variables
Numeric Operations
- Python supports basic *, /, +, -
- Python also supports floor division
1//3 #returns 0
1/iii #returns 0.333 - Additionally, python supports exponentiation via ** operator:
two**3 = 2 * two * 2 = 8 - Python supports Modulus (remainder) operator too:
vii%2 = one There is too a divmod in-built method. It returns the divider and modulus:
print(divmod(10,3)) #it volition impress 3 and 1 as 3*iii = 9 +1 = x String Operations
Concat Strings:
'A' + 'B' = 'AB' Think string is an immutable information type, therefore, concatenating strings creates a new string object.
Repeat String:
'A'*three will repeat A iii times: AAA Slicing:
y = 'Abc'
y[:2] = ab
y[one:] = bc
y[:-2] = a
y[-2:] = bc Reversing:
10 = 'abc'
10 = 10[::-1] Negative Alphabetize:
If yous want to start from the last grapheme and then employ a negative alphabetize.
y = 'abc'
print(y[:-i]) # will return ab Information technology is likewise used to remove any new line carriages/spaces.
Each element in an assortment gets two indexes:
- From left to correct, the index starts at 0 and increments by 1
- From right to left, the index starts at -1 and decrements past 1
- Therefore, if we exercise y[0] and y[-len(y)] then both volition return the same value: 'a'
y = 'abc'
print(y[0])
print(y[-len(y)]) Finding Alphabetize
name = 'farhad'
alphabetize = name.find('r') #returns 2 name = 'farhad'
index = proper name.notice('a', 2) # finds index of 2d a #returns 4
For Regex, use:
- split(): splits a string into a listing via regex
- sub(): replaces matched cord via regex
- subn(): replaces matched string via regex and returns the number of replacements
Casting
- str(x): To cord
- int(x): To integer
- float(x): To floats
- tuple(list) : To tuple: print(tuple([1,2,3]))
- list(tuple(1,ii,three)): To list: impress(list((1,ii,iii)))
Recall list is mutable (tin can be updated) and tuple is immutable (read-but)
Set Operations
- The fix is an unordered data collection without any duplicates. We can ascertain a set variable as:
a = {1,2,iii} Intersect Sets
- To get what'south mutual in two sets
a = {i,2,3}
b = {iii,4,5}
c = a.intersection(b) Difference In Sets
- To retrieve the divergence between the 2 sets:
a = {ane,two,3}
b = {3,4,v}
c = a.deviation(b) Union Of Collections
- To become a distinct combined set of two sets
a = {one,2,3}
b = {3,4,5}
c = a.union(b) Ternary Operator
- Used to write conditional statements in a single line.
Syntax:
[If True] if [Expression] Else [If Faux]
For example:
Received = True if x == 'Yeah' else Fake Object Identity
I will attempt to explain the of import subject of Object Identity now.
Whenever we create an object in Python such as a variable, part, etc, the underlying Python interpreter creates a number that uniquely identifies that object. Some of the objects are created upwards-front.
When an object is not referenced anymore in the code and then information technology is removed and its identity number can exist used by other variables.
- Python lawmaking is loaded into frames that are located into a Stack.
- Functions are loaded in a frame along with their parameters and variables.
- Subsequently, frames are loaded into a stack in the right lodge of execution.
- Stack outlines the execution of functions. Variables that are declared outside of functions are stored in __main__
- Stacks executes the concluding frame first.
You lot can use traceback to detect the list of functions if an error is encountered.
dir() and help()
- dir() -displays divers symbols
- assist() — displays documentation
Let's empathize it in item:
Consider the code below:
var_one = 123
def func_one(var_one):
var_one = 234
var_three = 'abc' var_two = 456
impress(dir())
var_one and var_two are the ii variables that are defined in the code above. Forth with the variables, a function named func_one is also defined. An of import annotation to proceed in heed is that everything is an object in Python, including a office.
Within the function, nosotros have assigned the value of 234 to var_one and created a new variable named var_three and assigned it a value of 'abc'.
Now, let'southward understand the code with the help of dir() and id()
The above code and its variables and functions will be loaded in the Global frame. The global frame will concord all of the objects that the other frames crave. As an example, at that place are many built-in methods loaded in Python that are available to all of the frames. These are the role frames.
Running the above lawmaking will print:
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'func_one', 'var_one', 'var_two' ] The variables that are prefixed with __ are known every bit the special variables.
Notice that the var_three is not available still. Permit's execute func_one(var_one) so assess the dir():
var_one = 123
def func_one(var_one):
var_one = 234
var_three = 'abc' var_two = 456
func_one(var_one)
print(dir())
We will again meet the aforementioned list:
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'func_one', 'var_one', 'var_two'] This means that the variables inside the func_one are only within the func_one. When func_one is executed then a Frame is created. Python is tiptop-down therefore it always executes the lines from peak to the bottom.
The office frame can reference the variables in the global frame but whatever other part frame cannot reference the same variables that are created within itself. As an instance, if I create a new function func_two that tries to print var_three so it will neglect:
var_one = 123
def func_one(var_one):
var_one = 234
var_three = 'abc' var_two = 456
def func_two():
print(var_three) func_one(var_one)
func_two()
impress(dir())
We get an fault that NameError: proper name 'var_three' is non defined
What if we create a new variable inside func_two() and then print the dir()?
var_one = 123
def func_one(var_one):
var_one = 234
var_three = 'abc' var_two = 456
def func_two():
var_four = 123
print(dir()) func_two()
This will print var_four as it is local to func_two.
How does Assignment work In Python?
This is by far one of the about important concepts to empathize in Python. Python has an id() function.
When an object (function, variable, etc.) is created, CPython allocates information technology an address in memory. The id() function returns the "identity" of an object. It is substantially a unique integer.
As an instance, allow's create four variables and assign them values:
variable1 = 1
variable2 = "abc"
variable3 = (1,two)
variable4 = ['a',i] #Print their Ids
print('Variable1: ', id(variable1))
print('Variable2: ', id(variable2))
print('Variable3: ', id(variable3))
print('Variable4: ', id(variable4))
The ids will exist printed as follows:
Variable1: 1747938368
Variable2: 152386423976
Variable3: 152382712136
Variable4: 152382633160
Each variable has been assigned a new integer value.
The get-go assumption is that whenever we apply the assignment "=" and then Python creates a new memory address to store the variable. Is it 100% true, not actually!
I am going to create two variables and assign them to the existing variables.
variable5 = variable1
variable6 = variable4 impress('Variable1: ', id(variable1))
print('Variable4: ', id(variable4))
print('Variable5: ', id(variable5))
print('Variable6: ', id(variable6))
Python printed:
Variable1: 1747938368
Variable4: 819035469000
Variable5: 1747938368
Variable6: 819035469000
Notice that Python did not create new memory addresses for the two variables. This time, it pointed both of the variables to the same retention location.
Permit'southward set a new value to the variable1. Recall 2 is an integer and integer is an immutable data type.
impress('Variable1: ', id(variable1))
variable1 = 2
print('Variable1: ', id(variable1)) This will impress:
Variable1: 1747938368
Variable1: 1747938400
It means whenever we utilize the = and assign a new value to a variable that is not a variable reference then internally a new retentivity address is created to shop the variable. Let'southward come across if it holds!
What happens when the variable is a mutable data type?
variable6 is a list. Permit'south append an item to it and impress its memory address:
impress('Variable6: ', id(variable6))
variable6.append('new')
print('Variable6: ', id(variable6)) Note that the memory address remained the same for the variable as it is a mutable data type and we just updated its elements.
Variable6: 678181106888
Variable6: 678181106888
Let's create a function and laissez passer a variable to it. If nosotros set the value of the variable within the office, what will it practise internally? let's assess
def update_variable(variable_to_update):
print(id(variable_to_update))
update_variable(variable6)
impress('Variable6: ', id(variable6))
We become:
678181106888
Variable6: 678181106888
Find that the id of variable_to_update points to the id of the variable 6.
This means that if we update the variable_to_update in a function and if variable_to_update is a mutable data type and so we'll update variable6.
variable6 = ['new']
print('Variable6: ', variable6 def update_variable(variable_to_update): variable_to_update.suspend('inside') update_variable(variable6)
print('Variable6: ', variable6)
This printed:
Variable6: ['new']
Variable6: ['new', 'within']
It shows us that the aforementioned object is updated within the function as it was expected considering both of them had the same ID.
If nosotros assign a new value to a variable, regardless of if it'due south immutable and mutable information type then the alter will be lost once nosotros come out of the office:
print('Variable6: ', variable6) def update_variable(variable_to_update):
impress(id(variable_to_update))
variable_to_update = ['inside'] update_variable(variable6)
print('Variable6: ', variable6)
Variable6: ['new']
344115201992
Variable6: ['new']
Now an interesting scenario: Python doesn't always create a new memory accost for all new variables. Let me explain.
Finally, what if we assign two unlike variables a string value such as 'a'. Will it create 2 memory addresses?
variable_nine = "a"
variable_ten = "a"
print('Variable9: ', id(variable_nine))
impress('Variable10: ', id(variable_ten)) Observe, both the variables have the same retentiveness location:
Variable9: 792473698064
Variable10: 792473698064
What if we create two different variables and assign them a long string value:
variable_nine = "a"*21
variable_ten = "a"*21
print('Variable9: ', id(variable_nine))
impress('Variable10: ', id(variable_ten)) This time Python created 2 retentivity locations for the two variables:
Variable9: 541949933872
Variable10: 541949933944
This is because Python creates an internal cache of values when information technology starts upward. This is done to provide faster results. It creates a scattering of memory addresses for minor integers such as between -5 to 256 and smaller string values. This is the reason why both of the variables in our case had the same ID.
This article explained how variables are assigned.
If y'all desire to empathise Python in particular then read this article:
blackariervintend01.blogspot.com
Source: https://towardsdatascience.com/python-variable-assignment-9f43aed91bff
0 Response to "if a python function attempts to assign a value to a variable that is in global scope, what happens?"
Enviar um comentário