Data types & Variables | Learning Python Part - 2

An introduction to data types, variables & type conversion
Posted by Sarav, 4 years ago on Python

In this part of Python Learning series, we are going to look at the different data types that are available in python and variables.

I will walk you through step by step on how to create variables, assign value, and consume in your logic. In the first part of this tutorials series, we installed the necessary tools we need and I am going to use Jupyter Notebook throughout this learning series.

Data types

Data types are input types that python recognizes and accepts into a programming language. A programmer uses these data types for defining, declaring, storing, and performing any logical or mathematical operations. Data types form the foundation of any programming language so does Python. There any many data types available in Python not limited to user-defined types. As we all know Python is an Object-Oriented Programming language, it allows users to create classes that are basically a data type. Apart from user-defined types, there are 7 major data types that are commonly used in Python and these are,

  • Number
  • String
  • Boolean
  • List
  • Tuple
  • Set
  • Dictionary

 

Numbers

As the name suggests, this data type is used to store and manipulate numerical values. Numerical values are further classified into Integers, Floats, and Complex

Integers are whole numbers without any decimal places and one common use of Integers is to count in a loop.
e.g., one = 1, two = 2

Floats sometimes called Double values are the data type used to store numbers with decimal places e.g., calculating percentages, bank transactions, etc., where the decimal places are important.
e.g., percent = 93.5, total = 1086.03

 Complex data type represents a complex number with real and imaginary parts.
e.g., comp = 3 + 9j

 

String

The string data type is used to represent a Text or otherwise string of Characters. Basically, the string type is a list of characters joined together to form a word. A string is always inclosed between single-quotes or double-quotes. Python allows the use of both single and double quotes and also the user is allowed to mix both. However, as a good programming practice, you should stick to one type. However, under certain special circumstances, we use both single and double quotes in the same line.

e.g., website = 'This website is awesome!' or website = "This website is awesome!"

 

Boolean

Boolean is used to store either True or False which represents On / Off condition. Most commonly used in logical expressions to evaluate the state of the logic, say True or False.
e.g., is_working=True

 

Lists

The list data type is used to store a collection of different data types. Unlike, other programming languages, Python allows us to store different data types on the same list. One important feature is list is, it is mutable i.e., you can modify the elements of the list as you wish. The list is represented by square brackets []
e.g., Marks = [98, 63.5, 45, 98, 100]

Elements of a list can be accessed by using [] square brackets and passing the index of the element. To access the first element 
elem1 = Marks[0]
to access the second element, we need to pass 1 as an index
elem2 = Marks[1]


As I, pointed out earlier, Lists are mutable, we can change the element and assign a new value and that can be a different data type.


e.g., Marks[0] = "Modified"
Now, the list becomes
Marks = ["Modified", 63.5, 45, 98, 100]

 

Tuples

The tuples data type is similar to list and the main difference is Tuples are immutable i.e., we are not allowed to change the elements inside a tuple. However, we can change the entire tuple by destroying it and creating a new one. We use an open and close parentheses ( ) or the keyword tuple([]) to declare a tuple.
e.g., tup = (1,2,3,4.5,3,6)

We can access the elements of tuple by using [] square brackets.
element1 = tup[0]
element2 = tup[1]

We cannot change the elememnt of a tuple, but the following operation is allowed.
tup = (1.1, 1.2, 3.2) 

 

Sets

Sets are similar to Lists & Tuples used to store a collection of elements, but the main difference is, sets are immutable and unique. Set allows us to store only unique elements with no precise order (i.e., unordered) and duplicates will be discarded. To create a set we use the keyword set([]) or curly braces { }.
e.g., unique_marks = { 1, 2, 3, 4, 5, 5 }
if we execute the above code is Python, we get the following result
unique_marks = { 1, 2, 3, 4, 5 }

 

Dictionary

Dictionary is also used to store a collection of data types but in the form of key-value pair. It is an ordered mutable collection with unique keys. Dictionary is one of the most important data type used in Python and this closely resembles Json, JavaScript Object Notation. We will use Json in our Flask learning series. To create a dictionary we can use curly braces similarly to sets or the keyword dict(x=y, a=b)
e.g., marks = dict(a=1, b=5, c=6)

or
marks = { 

       'a' : 1,
       'b' : 5,
       'c' : 6
}

both of the above produces the same result.

As we progress through this learning series we frequently use all of the above data types equally in our programming tasks.

 

Exercise

Let's practice all of the above data types using a Jupyter Notebook. Open a Notebook session by running the command
jupyter notebook 
in a terminal or command window.

  • Create a notebook by clicking on "New"

  • Alright, now we are all done with the environment setup. First, let's start with creating Numbers and common mathematical operations.
    # Creating Integers
    int_variable = 1
    
    # Creating Float / Double
    float_variable = 3.141
    
    # Boolean
    bool_variable = True
  • To run or execute the above piece of code in Jupyter Notebook, select the cell and press "Shift" + "Enter".Next, let's examine the data types of the above variables
    #Let's examine the data type of the above varialbes.
    
    print("int_variable : ", type(int_variable))
    
    print("float_variable : ", type(float_variable))
    
    print("bool_variable : ", type(bool_variable))

  • Now, let's perform basic arithmetic operations.
    # Arithmetic operations with Python
    
    var_1 = 10
    var_2 = 3.0
    
    # Addition
    
    sum_of_var = var_1 + var_2
    
    # Subtraction
    
    difference = var_1 - var_2
    
    # Multiplication
    
    product = var_1 * var_2
    
    # Division with decimal places
    
    div = var_1 / var_2
    
    # Division without decimal places or floor division ( in other words, get the quotient)
    
    quotient = var_1 // var_2
    
    # Modulus or get the reminder
    
    reminder = var_1 % var_2
    
    # Let's print out the results
    
    print(f"var_1 : {var_1}")
    print(f"var_2 : {var_2}")
    
    print(f"sum_of_var : {sum_of_var}")
    print(f"difference : {difference}")
    
    print(f"product : {product}")
    
    print(f"div : {div}")
    print(f"quotient : {quotient}")
    print(f"reminder : {reminder}")
  • I hope we are clear on how to work with Numerical variables and to perform basic arithmetic operations. Now, let's look at some examples of strings & string manipulation.
    # String & String Manipulation
    
    firstname = "Jarvis" 
    
    # or 
    
    lastname = 'Intelligent System'
    
    # If we check the type 'firstname' & 'lastname' both will show as <class 'str'>
    print(f"firstname : {type(firstname)}")
    print(f"lastname : {type(lastname)}")
    
    # As I told earlier, the string is a list of characters, so we can access the individual character by specifying its index.
    
    print(firstname[0])
    
    # Now, we should get 'J' printed. Similarly, if we want the last character, then we can use the following code.
    
    print(lastname[-1])
    
    # In Python it's very easy to concatenate two strings, simply add them together.
    
    print(firstname + " " + lastname)
    
    # To get the number of characters in a string we can use the len() function, 
    #we will look at len() in details when we learn about Lists
    
    print(f"fistname has {len(firstname)} number of characters")
  • We will look at boolean in detail when we look at loops & conditional operations.
    # Create Boolean variable
    
    IsWorking = True
    
    print(f"IsWorking {IsWorking}")
    print(type(IsWorking))
  • Finally, we are into List, Tuples, Sets & Dictionary. Let's look at examples on how to create them and we will use these four datatypes extensively throughout our learning series.
    # Creating a List
    
    marks = [48, 56, 98, 32, 69, 79, 99, 100]
    
    # let's look at how to get the number of items in this list. As we saw earlier, we can use the len() function.
    
    marks_len = len(marks)
    
    print(marks)
    print("marks has " + str(marks_len) + " items")
    # [48, 56, 98, 32, 69, 79, 99, 100]
    # marks has 8 items
    
    
    # Creating a tuple
    
    tup = (5,6,9,7,96,12,3,5,94,44)
    
    # we can use len on any iterable objects, therefore, we can use len() to find the number of itmes in tup
    
    tup_len = len(tup)
    
    print(tup)
    print("tup has " + str(tup_len) + " items")
    # (5, 6, 9, 7, 96, 12, 3, 5, 94, 44)
    # tup has 10 items
    
    
    # Creating a set 
    
    programming = {'Python', 'VB .NET', 'C#', 'C++', 'C', 'Python'}
    # or it's the same as programming = set(['Python', 'VB .NET', 'C#', 'C++', 'C', 'Python'])
    
    # I intentionally, tried to add 'Python' twice, but we know that set contains unique 
    #items, so the second 'Python' is discarded
    
    print(programming)
    # {'C', 'C++', 'C#', 'VB .NET', 'Python'}
    
    
    #Creating a Dictionary
    
    avengers = {'Iron Man': 'Tony Stark',
     'Hulk': 'Bruce Banner',
     'God of Thunder': 'Thor',
     'Black Widow': 'Natsha',
     'Hawk-Eye': 'Clint'}
    
    print(avengers)
    #avengers = {'Iron Man': 'Tony Stark',
    # 'Hulk': 'Bruce Banner',
    # 'God of Thunder': 'Thor',
    # 'Black Widow': 'Natsha',
    # 'Hawk-Eye': 'Clint'}
    

Type Conversion

So far we have seen how to create variables. Now, we will look at how to convert one type into another. Let's look at some basic examples.

# Convert int to float

float1 = 5.0 # This will create a floating point number
int1 = 5 # This will create a integer variable, 

# Threfore, to create a float variable, we simply need to declare the varible with floating point decimal places.

float2 = 3.141592653589793238

# to drop all the decimal places and to get only the whole number
to_int = int(float2)
print("to_int : ", to_int)
# this should output to_int : 3


# Convert string to int or float. Let's say we have a sting variable byt in a string format, 
#we can simply use the following code to convert it back to int or float

var1 = "3.141592653589793238"

print(float(var1))

# we cannot simply convert a string float into int directly. 
#First we need to convert it into a float and then apply int function on it.
print(int(float(var1)))

# Now, lets convert a float or int to string.

str1 = str(var1)
str2 = str(int1)

print(str1)
print(str2)

# Great!, Let's see how to convert between, List, Tuple, and Set

avengers_list = ['Tony', 'Bruce', 'Peter', 'Valkyrie', 'Thanos', 'Tony']

avengers_tuple = tuple(avengers_list)

avengers_set = set(avengers_list)

# convert a set / tuple to list we can simply apply list() to it

new_list = list(avengers_set)

print(f"avengers_list : {avengers_list}")
print(f"avengers_tuple : {avengers_tuple}")
print(f"avengers_set : {avengers_set}")

print(f"new_list : {new_list}")

# The above code should print out the following output.

# to_int :  3
# 3.141592653589793
# 3
# 3.141592653589793238
# 5
# avengers_list : ['Tony', 'Bruce', 'Peter', 'Valkyrie', 'Thanos', 'Tony']
# avengers_tuple : ('Tony', 'Bruce', 'Peter', 'Valkyrie', 'Thanos', 'Tony')
# avengers_set : {'Tony', 'Peter', 'Valkyrie', 'Thanos', 'Bruce'}
# new_list : ['Tony', 'Peter', 'Valkyrie', 'Thanos', 'Bruce']

That's all for this tutorial, folks. We will take a deep dive into each data type in our subsequent tutorials.

If you would like to download the notebook, Click Here.

Similar Topics

Let's understand for & while loop visually

Posted by Sarav, 4 years ago on Python Learning Python

A gentle introduction to if, else & elif and for & while loops.

Posted by Sarav, 4 years ago on Python Learning Python

Installing python & jupyter notebook on windows & linux platform, a minimalistic approach.

Posted by Sarav, 4 years ago on Python Learning Python