Python Variables
A variable is a name given to a memorable place that has been set aside. When a variable is declared in a programme, it sets aside some memory for storing its value(s), and the interpreter allocates memory for that variable based on its datatype. The variable’s value(s) are saved by assigning multiple data types to it, such as numbers, strings, and sequences. Let us start with Python Variables.
Variable Declaration
Python, unlike Java and C++, does not need the declaration of a variable or its data type. When a value is assigned to a variable, the data type is set. The = operator is used to assign a value(s) to the variable.
#store number in the variable 'x' x = 15 print(x) #store text in the variable 'y' y = 'Hello' print(y) #store sequence in the variable 'z' z = [1, 2, 3] print(z)
The output of the code will be:
15 Hello [1, 2, 3]
When a new value is assigned to a variable in Python, the previous value and datatype are overwritten by the new value and datatype.
#variable 'x' holds integer datatype with value 15 x = 15 #Now, variable 'x' holds string datatype with value 'Hello' x = 'Hello' print(x)
The output of the code will be:
Hello
Parallel Assignment
Python also allows you to assign variables in parallel. This allows you to initialise numerous variables with only one line of Python code. Consider the following scenario:
x , y = 15, 20.5 print(x) print(y,"\n") x, y = [1, 2, 3], ('red', 'blue', 'green') print(x) print(y)
The output of the code will be:
15 20.5 [1, 2, 3] ('red', 'blue', 'green')
Print Variable
The print() method can be used to print the variable’s value on the screen or another standard output device. The comma (,) operator is used to concatenate string values of variables with whitespace inside the print() method to combine string values of two or more variables.
MyStr = "John" MyNumber = 25 print(MyStr, "is", MyNumber, "years old.") x = 50 y = 30 print(x, y)
The output of the code will be:
John is 25 years old. 50 30
It can also be done using the plus (+) character, although there are certain limitations. Also, It joins together two or more variables of the same data. It returns concatenated variables for string datatypes and the sum of variables for numeric datatypes. It will throw an exception if the data types are mixed.
MyStr = "John" MyLocation = "London." print(MyStr + " Lives in " + MyLocation) x = 25 y = 10 print(x + y) #Mixing datatypes will raise an exception print(MyStr + "is" + x + "years old.")
The output of the above code will be:
John Lives in London.
35 Traceback (most recent call last): File "Main.py", line 10, in <module> print(MyStr + "is" + x + "years old.") TypeError: can only concatenate str (not "int") to str
To attain the desired output, you can use the comma (,) and plus (+) characters in the print() method at the same time.
x = 25 y = 10 print("sum of", x,"and", y,"is", x+y)
sum of 25 and 10 is 35
Variable Name
In Python, there are several reserved terms that cannot be used as variable names. In addition, the following are some guidelines for naming Python variables:
- It must start with a letter or the underscore character
- The variable cannot start with a number.
- It can only contain alpha-numeric characters and underscores (A-Z, a-z, 0-9, and _ ).
Please keep in mind that Python is case-sensitive. As a result, variables in Python are case-sensitive as well.
Global Variable
A global variable is one that is generated outside of a function. A global variable can be referenced both within and outside of the function.
Example
A global variable, MyStr, is created and utilised inside the function to print it in the example below.
MyStr = "Hello World!" def MyPrint(): print(MyStr) MyPrint()
The output of the above code will be:
Hello World!
If you create a variable with the same name inside the function, it will be a local variable that can only be used within the function. Any action on a local variable has no effect on the global variable.
Example
A variable called MyStr is given various values within and outside the function in the example below. When the variable is accessed outside of the function, it takes its global value, which is untouched by any operations performed on the local variable.
MyStr = "Hello World!" def MyPrint(): MyStr = "Hello John!" print(MyStr) #variable accessed inside function MyPrint() #variable accessed outside function print(MyStr)
The output of the above code will be:
Hello John! Hello World!
Python global keyword
The global keyword is used to create or access a global variable within a function. A global variable can be referenced both within and outside of the function.
Example
The global keyword is used to change and create global variables within a function in the example below.
MyStr = "Hello World!" def MyFunction(): #accessing and creating global variables #global variable MyMessage will be #created after function call global MyStr, MyMessage MyStr = "Hello John!" MyMessage = "Python programming is fun" MyFunction() #accessing variables outside function print(MyStr) print(MyMessage)
The output of the above code will be:
Hello John! Python programming is fun