A Crash Course in Python Variables

There’s around 12 categories that your variable could fall into.IntegersFloatsComplex NumbersBooleanStringsListsTupleRangeDictionariesMutable SetsImmutable SetsEveryone’s feeling it too :/I’m going to pull up the code for a quick referencex=2y=2if type(x) == type(y): print("X and Y have the same type")Since X and y are both integers ( 2 is a real numbers ), they have the same type and therefore the statement evaluates to true.Some types you will be encountering a bit more frequently will beStrings ( Eg. “Anna” , “John”)Lists (Eg. [1,2,3,4] OR [1,2, “Anna” , “John”] )Floats (1.02 — Note the addition of decimal places!)Dictionaries ({“brand”: “Nissan”, “model”: “GTX1000”, “year”: 2018}ValueLastly, we’ve got the value of an integer.x=2y=2if x == y: print("X and Y have the same value")This is what you initialise your variable to be..When you declare a variable, you are assigning a value to it..( Eg. x = 2 , you declare the value of x to be 2 )So, to recap, a variable is an object with a type, a value and an identity! Once you’ve gotten the hang of these three components of a variable, you’re good to go! You’re just left with understanding the scope of an object :)ScopeEach time a function is executed, a new local namespace is created.For instance, imagine this code#Redeclaring Variablesx = 3 #X is now declared as 3 at memory location xx = 5 #X is now declared as 5 by shifting the reference pointer of x to another object 5#Scope Wisex = 3def function(): x = 2 #These are all different instances of X..Each X lives within each individual scope, the first at a global level, the second at a function specific level and the last in the conditional loop it is nested withinThere are two namespaces within this code blockThe Global namespace where x = 3 exists withinThe Function namespace where x=2 exists withinIf I were to create an additional function within the function() function, it would then create an additional local enviroment.Here are the steps that the Python Interpreter takes to find codeIt first searches the local namespace to find the variable the code is referencing.If no match is found, it searches the global namespace..This can be accessed by using a global keyword.a = 10b = 20def myfunction(): global a a = 11print(a) #A is printed out as 11The global keyword allows your function to search the global namespace..Otherwise it will cause an error in your program.RecapHere’s a quick tl;dr of what we covered today.Variables have a type, an identity and a valueScope matters and functions can only access variables within their scope/local namespace. More details

Leave a Reply