Python Variables and Datatypes
Before we begin discussing Python Variables and Datatypes, it is important to understand more about data, which has surpassed oil as the most valuable resource in the world. Today’s world depends on data to steer forward and determine the complexity of issues, including pandemic situations, elections, and take appropriate decisions for those circumstances.
We have several kinds of data in the market. Let me explain to you in simplistic terms. You can view the entire information in this world in either numerical or alphabetical or graphical or through any other manner. And all that you will be looking for is to understand the data that comes to you. Since you have an amazing brain to process the information you gather from your surroundings, you will understand almost everything, even if it means that the information is knocking at the door of your brain through gestures.
We know that computers understand things only through codes and programs. That’s why the programmers segregate information accordingly to make the computers understand each piece of data. In Python, we achieve that through variables and datatypes. You will be surprised to see what Python Variable and Datatypes have in store to help us program easily and improve our lives. We will learn all about it in detail in this post, beginning with the topic of variables in Python
Also, Find links to all chapters of Python here: Learn Python
Python Variables – Everything you need to know
In our previous post, we discussed storing certain values while creating our first Python program. Let me share the same program once again here below. You can see that I stored the values of 30 to x and 10 to y to perform the subtraction operation. Entering the 30-10 in command line or IDLE window will also give you the same output as 20. However, I decided to store 30 and 10 to x and y as it gives me the privilege to not type the code again and again by storing the subtraction value in another variable, z. Though I entered this code in the command line window in the previous post, I can still save this program in a file and execute it any number of times without typing the code again and again.
#Let us write our first program of Python to subtract two numbers
x=30
y=10
z=x-y
print("Subtraction Result is ",z)
In this program, x, y, and z are the variables.
What happens when you declare a variable in Python?
- In Python, a variable is observed as a tag that is attached to a value
- As shown in the figure above, when you declare p=2 in Python, it means that a value 2 is created first in memory, and a tag p is mapped later
- q=p, in the next line of code, means a new tag q would also refer to 2 in the memory
- That’s why if you type the print statements of both print(p) and print(q), the same output 2 will be produced by Python
- If you type the code p=1, the p variable will be tagged to value 1, and the q variable will still be tagged to 2 unless you copy the variable once again with the command q=p. Let us understand it better using the program below.
#Simple Python code to understand variables in Python
p=2
q=p
print(p) #displays 2
print(q) #displays 2
p=1
print(p) #displays 1
print(q) #displays 2
Output
>>> p=2
>>> q=p
>>> print(p)
2
>>> print(q)
2
>>> p=1
>>> print(p)
1
>>> print(q)
2
Python Datatypes
As mentioned above, it is important to segregate data or assign each piece of data as a type, and we use Datatypes for the same in Python. We have two kinds of datatypes in Python, which are Built-in Datatypes and User-Defined datatypes. We will explore the User-Defined datatypes in the future chapters and look into the Built-in datatypes of Python in detail in this post.
Python Built-in Datatypes
The built-in Datatypes in Python are broadly classified into the following categories. Each one of them is further divided into sub-categories and we will go through each one of them in detail.
- None Type
- Numeric
- Sequences
- Sets
- Mappings
1. None Type
In Python, None Type refers to an object that does not contain any value. In other programming languages such as Java, it is called Null. But we call it as None in Python. In Boolean expressions, the None type refers to False. Let us now look into how Python deals with Boolean expressions.
bool Datatype
Python uses bool datatype to use the boolean expressions in its programs. Both the boolean values, True and False, can be expressed by this datatype. In the background, Python assigns True as 1 and False as 0. As mentioned in the None type section of this post, an empty string such as “” is also expressed as False.
a="" #assigning an empty value to variable a
print(bool(a)) #printing the boolean value of a variable
True+True #This will display the output of 2 as True is assigned as 1 in Python
True-False #This will display the output as 1 as True is 1 and False is 0 in Python
Output
>>> a=""
>>> print(bool(a))
False
>>> True+True
2
>>> True-False
1
In Python, the conditions are evaluated to be either True or False. Let us understand more about that using a program below.
p=15
q=25
if(p<q): print("Laptop") #displays Laptop
Output from Python Command Line Window
>>> p=15
>>> q=25
>>> if(p<q): print("Laptop")
...
Laptop
In the aforementioned code, the condition in the third line of code is evaluated to be True as 15 stored in p is less than 25 stored in q and that’s why the Laptop is printed as the output. If you’d mention the condition as p>q for the same values, nothing gets printed as this condition would be evaluated to be False. Let us have a look at one more example below.
p=25>15 #p gets handled as bool type variable
print(p) #displays True
p=25<15 #p gets handled as bool type variable
print(p)# displays this time False as 25 is not less than 15
Output
>>> p=25>15
>>> print(p)
True
>>> p=25<15
>>> print(p)
False
2. Numeric Datatypes
Just as the name sounds, it refers to the kind of data in numbers. Listed below are the types of Numeric datatypes in Python
- int
- float
- complex
2.1 int Datatype
The int datatype refers to the integer numbers that do not have a fraction or any decimal point. For example, both -50 and 40 are integers, and even the 0 is also an integer. If you declare any variable with an integer value, the Python will declare the datatype as int dynamically for the same variable. Let us now look at an example below.
a=40
print(type(a)) #this will display the type of the variable a
Output
>>> a=40
>>> print(type(a))
<class 'int'>
You can see that we added a value of 40 to the variable a, in the program above. When we tried to display the type of the variable using the type() function on the next line of code, it displayed <class ‘int’>. Since Python uses the available memory when an integer is declared, there is no boundary for the size of an int datatype.
2.2 float Datatype
We all know that floating-point numbers represent numbers with decimal points such as 0.7, -8.5, or 125.36. And we use the float Datatype to assign these values in Python programs. Like int Datatype, you can declare any variable with a float number and the Python will declare the datatype as float dynamically for the same variable. Let us now look at an example below.
a=77.7
print(type(a)) #this will display the type of variable a
Output
>>> a=77.7
>>> print(type(a))
<class 'float'>
You can see that we added a value of 77.7 to the variable a, in the program above. When we tried displaying the type of the same variable using the type() function on the next line of code, it displayed <class ‘float’>. The exponential numbers such as 2.7E7 or 33.77e3 are also designated as floating-point numbers in Python.
2.3 Complex Datatype
A complex number follows the standard of a+bj or a+bJ, where a is the real component of the number and b is the imaginary section of the number. Also, you should follow either j or J in a complex number and not with any other alphabet. It refers to the square root value of -1. For example, the following numbers are all complex numbers.
- 0.5+11.5J
- -2-7.5j
- 3+7j
The numbers listed above are all complex numbers and let us now look at an example of how it is used in the programs.
a=3+7j #assigning a complex number to the variable a
print(type(a)) #this will display the type of the a variable as complex
Output
>>> a=3+7j
>>> print(type(a))
<class 'complex'>
When we added a complex number 3+7j to the variable a and tried displaying its type in the next line of code using the type() function, it displayed <class ‘complex’>.
Binary, Octal, and Hexadecimal numbers in Python?
- Binary Number is represented by prefixing 0b(zero and b) or 0B(zero and B) before the value. Examples are 0b110110 or 0B110110.
- Hexadecimal Number is represented by prefixing 0x(zero and x) or 0X(zero and X) before the value. Examples are 0xA180 or 0XA180.
- Octal number is represented by prefixing 0o(zero and o) or 0O(zero and O) before the value. Examples are 0o777 or 0O777
Type Conversion in Python
By this time, you must have understood that Python declares variables on its own. However, there could be situations where you might want to convert the datatype of a variable into another type on its own. You can achieve the same using Type Conversion in Python. Let us look at an example below.
a=10.5 #declaring a floating type number to variable a
print(int(a)) #converting from float to int and printing the output
b=7 #declaring an integer type number to variable b
print(float(b)) #converting from int to float and printing the output
c=3 #declaring an integer type number to variable c
print(complex(c)) #converting int to complex and printing the output
Output
>>> a=10.5
>>> print(int(a))
10
>>> b=7
>>> print(float(b))
7.0
>>> c=3
>>> print(complex(c))
(3+0j)
As you can see in the code mentioned above, type conversion is possible by specifying the datatype with parentheses. Example: float(number) or int(number) or complex(number). This is one of the wonders you can do with Python Variables and Datatypes.
3. Sequence
Python Sequences refer to a group of items or elements. Python has six kinds of sequences and they are listed below.
- str
- bytes
- bytearray
- list
- tuple
- range
3.1 str Datatype
In Python, str refers to string datatype. A group of string characters can be included in single-quotes or double-quotes.
str1 ="Hello" #used double quotes
print(str1)
str2 = 'Hello' #used single quotes
print(str2)
Output
>>> str1="Hello"
>>> print(str1)
Hello
>>> str2='Hello'
>>> print(str2)
Hello
You can also create a string with multiple sentences including spaces using triple double quotes (“””) as shown in the example below.
str3=""" i-Sapna.com is all about learning
and living. Join us in our journey
and let's make the world a better place together"""
Output from Python Command Line Window
>>> str3=""" i-Sapna.com is all about learning
... and living. Join us in our journey
... and let's make the world a better place together"""
>>> print(str3)
i-Sapna.com is all about learning
and living. Join us in our journey
and let's make the world a better place together
You can also use the triple-double quotes or triple-single quotes to create the string with single quotes or double quotes, as shown in the example below.
str4=""" Using 'single-quotes' and "double-quotes" as an example. """
Output from Python Command Line Window
>>> str4=""" Using 'single-quotes' and "double-quotes" as an example. """
>>> print(str4)
Using 'single-quotes' and "double-quotes" as an example.
The slice operator in Python has brackets [ and ] to display each piece of character from a string in the output. The index of the characters begins at 0, which means the first character of the string has the index zero. Let us find what the slice operator can offer for the string statements in the example below
s="Welcome to i-Sapna" #declare a string with set of characters in it
print(s[0]) #since index begins at 0, this will print the first character W
print(s[11:18]) #displays characters from index position 11 till 18
print(s[11:]) #displays character from index position 11 till end
print(s[-5]) #displays 5th character from the end
Output
>>> s="Welcome to i-Sapna"
>>> print(s[0])
W
>>> print(s[11:18])
i-Sapna
>>> print(s[11:])
i-Sapna
>>> print(s[-5])
S
You can use the symbol * to display the output any number of times as shown in the example below.
str5="i-Sapna " #declare a string
print(str5*5) #display the string five times in output
Output
>>> str5="i-Sapna "
>>> print(str5*5)
i-Sapna i-Sapna i-Sapna i-Sapna i-Sapna
3.2 bytes Datatype
The bytes refer to the numbers from 0 till 255 and the bytes array can also save numbers in the scale from 0 till 255 as shown in the example below.
items=[5,30,40,10,7] #declares a list of numbers
a=bytes(items) #converts the list to bytes array
print(a[3]) #displays the number in index 4
for i in a: print(i) #displays all the elements
Output
>>> items=[5,30,40,10,7]
>>> a=bytes(items)
>>> print(a[3])
10
>>> for i in a: print(i)
...
5
30
40
10
7
3.3 bytearray Datatype
The bytearray datatype also behaves like the bytes datatype. The major difference between both the datatypes is that the elements in the bytes array cannot be updated, and the bytearray allows users to update either one element or all of them in an array.
#python program to explore bytearray Datatype
items=[5,30,40,10,7] #declares a list of numbers
b=bytearray(items) #converts the list to bytearray
b[0]=77 #updating first element in array to 77
b[1]=33 #updating second element in array to 33
for i in b: print(i) #displays all the elements
Output
>>> items=[5,30,40,10,7]
>>> b=bytearray(items)
>>> b[0]=77
>>> b[1]=33
>>> for i in b: print(i)
...
77
33
40
10
7
You can see in the program above that we replaced the first and second and values of 5 and 30 with 77 and 33 respectively. This is not possible with bytes array datatype and is possible only with bytearray Datatype
3.4 list Datatype
If you are already familiar with languages like C and Java, you might have some idea about the concept of lists already. Nevertheless, the lists in Python refer to a group of elements. Sounds more like an array, isn’t it? But you are wrong. Because in arrays, we can store only a list of similar type and in lists, we can store elements of any types.
Another significant difference between the lists and the arrays is that you can increase the size of lists dynamically while the size of an array is fixed. The lists in Python are created between the brackets, [ and ] as shown in the example below.
#Python program to explore the concepts of lists
list1=[5,-10,"i-Sapna",7] #declares a list
print(list1) #displays all the elements in the list
print(list1[2]) #displays the element in index number 2
print(list1[2:]) #displays all the elements from index number 2 till end
print(list1*3) #displays the declared list 3 times
Output
>>> list1=[5,-10,"i-Sapna",7]
>>> print(list1)
[5, -10, 'i-Sapna', 7]
>>> print(list1[2])
i-Sapna
>>> print(list1[2:])
['i-Sapna', 7]
>>> print(list1*3)
[5, -10, 'i-Sapna', 7, 5, -10, 'i-Sapna', 7, 5, -10, 'i-Sapna', 7]
3.5 tuple Datatype
The tuple Datatype is also like a list, but there are a few differences. For instance, you can update the elements in the list, but you cannot update the elements in a tuple, and it is basically only read-only. The declaration is also slightly different as you will need to use the brackets ( and ) to create the tuples. Let us have a look at the example below.
#python program to understand the concept of tuple datatype
tuple1=(5,-10,"i-Sapna",7) #declares a tuple
print(tuple1) #displays all the elements in tuple
print(tuple1[2]) #displays the element in index number 2
print(tuple1[2:]) #displays all the elements from index number 2 till end
print(tuple1*3) #displays the declared tuple 3 times
tuple1[0]=88 #this will throw an error as you cannot update elements in tuple
Output
>>> tuple1=(5,-10,"i-Sapna",7)
>>> print(tuple1)
(5, -10, 'i-Sapna', 7)
>>> print(tuple1[2])
i-Sapna
>>> print(tuple1[2:])
('i-Sapna', 7)
>>> print(tuple1*3)
(5, -10, 'i-Sapna', 7, 5, -10, 'i-Sapna', 7, 5, -10, 'i-Sapna', 7)
>>> tuple1[0]=88
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>>
3.6 range Datatype
The range datatype is perhaps the easiest datatype in Python as it makes the declaration of the range of elements very easy. For example, if you were to declare range(7) in your python code, it will create a range object starting from 0 to 6.
#python program to explore the concept of range Datatype
a=range(7) #declares range from 0 to 6 and store them in a
for i in a: print(i) #this will display each element in a
Output
>>> a=range(7)
>>> for i in a: print(i)
...
0
1
2
3
4
5
6
#another python program to explore range Datatype
b=range(40,50,3)
for i in b: print(i)
Output
>>> b=range(40,50,3)
>>> for i in b: print(i)
...
40
43
46
49
In the second example program of the range Datatype mentioned above, we created a range object that begins from 40 and ends at 49. Since 3 is mentioned as the step size, the range in the output was incremented by 3 every time until it reached the end 49.
4. Sets
Like the idea of sets in math, a Set in Python also refers to a collection of elements that are not in order. It means that the elements in the set might not appear in the same way as they are entered into a set. There are two kinds of set datatypes in Python.
- set Datatype
- frozenset Datatype
4.1 set Datatype
In order to create a set in Python, you have to enter the elements divided by commas and within curly braces { and }.
#python program to explore the set Datatype
s={5,30,55,7} #declares a set s with elements
print(s) #displays the set s
s.update([77,40]) #adds two numbers 77 and 40 into set s
print(s) #displays the set s
s.remove(5) #removes the element 5 from the set
print(s) #displays the set s
Output from Python Command Line Window
>>> s={5,30,55,7}
>>> print(s)
{55, 5, 30, 7}
>>> s.update([77,40])
>>> print(s)
{5, 7, 40, 77, 55, 30}
>>> s.remove(5)
>>> print(s)
{7, 40, 77, 55, 30}
In the example program of set Datatype, you can observe that the elements were not printed in the declared order when we tried to display the declared set. We also made use of update() and remove() methods to add and remove the elements from the set.
4.2 frozenset Datatype
The frozenset Datatype also behaves much like the set Datatype. But the only major difference is that you cannot update a frozenset as you did with the set Datatype elements. It means that the methods update() and remove() will not work for any declared frozenset in Python.
#Python program to explore the frozenset Datatype
s={5,30,55,7} #declares a set s
print(s) #displays the elements in set s
fs1=frozenset(s) #create the frozenset fs1
print(fs1) #displays the elements in frozenset fs1
fs1.update([77,40]) #throws error as you cannot add or update in a frozenset
fs1.remove(55) #throws error as you cannot remove or update in a frozenset
Output
>>> s={5,30,55,7}
>>> print(s)
{55, 5, 30, 7}
>>> fs1=frozenset(s)
>>> print(fs1)
frozenset({55, 5, 30, 7})
>>> fs1.update([77,40])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'frozenset' object has no attribute 'update'
>>> fs1.remove(55)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'frozenset' object has no attribute 'remove'
5. Mapping Types
A map refers to a collection of elements in the order of key-value pairs. It means that by using a key, you can retrieve its corresponding value. The dict datatype is a case of a map in Python. You can separate the key and its value by a colon : and separate each pair by commas. All the elements should be included within the curly brackets {}.
#Python program to explore the dict Datatype
d={3:'i-Sapna',7:'Apple',40:'Success'} #creates a dictionary d
print(d) #displays both keys and values in d
print(d[7]) #displays the value related to the key 7
print(d.keys()) #displays all keys in dictionary d
print(d.values()) #displays all values in dictionary d
d[7]='Amazing' #updates the value of key 7 from Apple to Amazing
print(d) #displays both keys and values in d
del d[7] # deletes the key 7 and its corresponding value from d
print(d) #displays both keys and values in d
Output
>>> d={3:'i-Sapna',7:'Apple',40:'Success'}
>>> print(d)
{3: 'i-Sapna', 7: 'Apple', 40: 'Success'}
>>> print(d[7])
Apple
>>> print(d.keys())
dict_keys([3, 7, 40])
>>> print(d.values())
dict_values(['i-Sapna', 'Apple', 'Success'])
>>> d[7]='Amazing'
>>> print(d)
{3: 'i-Sapna', 7: 'Amazing', 40: 'Success'}
>>> del d[7]
>>> print(d)
{3: 'i-Sapna', 40: 'Success'}
We can do numerous operations on dictionaries, as mentioned in the program above. We can declare a dictionary with the desired set of key-value pairs, display them, display only the keys, display only the values, update the value for an existing key in the dictionary, and delete a key and its corresponding value. Try each one of them, and you will find the dictionaries more exciting to work with. However, we will explore this concept in detail in our future chapters.
In this post, we looked at Python Variables and Datatypes. You must have noticed that Python allows several complex matters surrounding the datatypes in other programming languages with an easy approach. We will explore everything else Python can offer us in our future chapters.
Share with us your experience of learning Python Variables and Datatypes in the comments section below. We would love to hear from you.