Python - Variables
Variable is a given name to a reserved memory location. When a variable is created in the program, it reserves some space in the memory to store value(s) and the interpreter allocates memory for the given variable based on its datatype. Value(s) is stored in the variable by assigning different datatypes to it like number, string and sequences, etc.
Variable Declaration
Unlike Java & C++, Python does not require to declare a variable or its data type. The data type of a variable is set when a value is assigned to it. To assign a value(s) to the variable, = operator is used.
#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 above code will be:
15 Hello [1, 2, 3]
In Python, when a new value is assigned to the variable, the old value and its datatype will be overwritten by new value and its 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 above code will be:
Hello
Parallel Assignment
Python also supports the parallel assignment of variables. This enables multiple variables to be initialized with a single line of Python code. Consider the example below:
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 above code will be:
15 20.5 [1, 2, 3] ('red', 'blue', 'green')
Print Variable
The value of the variable can be printed on the screen, or other standard output device using print() function. To combine string value of two or more variable inside print() function, comma (,) operator is used which concatenates string values of variables with a whitespace.
MyStr = "John" MyNumber = 25 print(MyStr, "is", MyNumber, "years old.") x = 50 y = 30 print(x, y)
The output of the above code will be:
John is 25 years old. 50 30
Alternatively, it can also be achieved with plus (+) character but with some limitation. It combines two or more variables of same datatypes. With string datatype, it returns concatenated variables and with number datatypes it returns sum of the variables. With mixed datatypes, it will raise an exception.
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
It is possible to use comma (,) and plus (+) characters inside print() function at the same time to get the desired result.
x = 25 y = 10 print("sum of", x,"and", y,"is", x+y)
The output of the above code will be:
sum of 25 and 10 is 35
Variable Name
There are some reserved keywords in Python which cannot be used as variable name. Along with this, rules for creating Python variable name are listed below:
- It must start with a letter or the underscore character
- It cannot start with a number.
- It can only contains alpha-numeric characters and underscores (A-Z, a-z, 0-9, and _ ).
Please note that Python is a case-sensitive language. Hence, variables in Python are also case-sensitive.
Global Variable
If a variable is created outside a function, it is called global variable. A global variable can be used anywhere, inside the function and outside the function.
Example
In the example below, a global variable MyStr is created and used inside the function to print it.
MyStr = "Hello World!" def MyPrint(): print(MyStr) MyPrint()
The output of the above code will be:
Hello World!
If a variable with same name is created inside the function, it will be a local variable and can be used inside the function only. Any operation performed on local variable will not change the global variable.
Example
In the example below, a variable MyStr is assigned different values inside and outside the function. When the variable is accessed outside the function, it takes global value and its global value remains unaffected by any operation done with 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
To create or access a global variable inside a function, global keyword is used. A global variable can be used anywhere, inside the function and outside the function.
Example
In the example below, the global keyword is used to modify and create global variable inside a function.
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