Learn Python for Data Science – Full Course

Learn Python for Data Science - Full Course

Learn Python for Data Science in this full course curated by the data science team at Kharpann.

In this course, you will learn how to install Python into your system, what are data structures, control flow tools in Python, input-output operations, errors and exceptions, classes and objects, standard libraries in Python and about virtual environments. Below is the complete list of chapters that will be covered in this Learn Python for Data Science – Full Course:

Chapter I: Installing Python and Getting Started

In this chapter, you will learn how to install Python on your operating system as well as how to write your first command in Python.

Unlike other popular programming languages (such as C and C++), Python uses an interpreter which is just a computer program that directly executes written instructions. This also means that all scripts written in Python are executed line by line and not all at once.

How to install Python on Windows, Mac OS X, Linux or any other operating system?

To install the Python interpreter, head on to Python’s official website and download the latest stable build of Python.

The installation process includes downloading the appropriate installer for your operating system and running it on your machine. Some OS (eg: Linux, macOS) provides a package manager that can be run to install Python. On some OS (eg: Android and iOS) you can install apps that provide a Python programming environment.

Getting Started with Python

Once you have installed Python on your system, it is time for you to check if it is working.

Open command prompt and type python. If a similar kind of interface appears on your prompt then you have successfully installed Python.

Note: Your python version may be different from the one shown in the photo.

Let’s try writing a simple Hello World program to see Python’s interpreter in action.

print("Hello, World!")

There you have it! You have installed Python and written your first Python code. Head onto the next chapter on Data Types and Operations in Python.

Chapter II: Data Types and Operations in Python

In this chapter, you will learn the various data types as well as operations used in Python.

Python contains a number of data types to make it easier for programmers to write functional and replicable programs. The different data types used in Python are listed below:

Data TypeExample
str‘Apple’, ‘Ball’
int123, 66, 222
float2.4, 3.21, 4.666
list[‘Python’, ‘C’, ‘C++’], [‘Nepal’, ‘USA’]
tuple(‘Python’, ‘C’, ‘C++’), (‘Nepal’, ‘USA’)
set{‘a’, ‘b’, ‘c’}, {1,2,3,4}
dict{‘Name’:’John’}, {‘id’:1, ‘age’: 48}
boolTrue, False

Strings (str) in Python

String literals in Python are surrounded by either single quotation marks or double quotation marks. The example below illustrates the basics of strings in Python:

# Basics of strings from input and output console example

# Defining a string using single qoutes
>>> 'spam eggs'  
'spam eggs'

>>> 'doesn\'t'  # use \' to escape the single quote...

>>> "doesn't"  # ...or use double quotes instead

>>> '"Yes," they said.' 
'"Yes," they said.'     # same output as input

>>> '"Isn\'t," they said.'
'"Isn\'t," they said.'

>>> print('"Isn\'t," they said.')
"Isn't," they said.

>>> s = 'First line.\nSecond line.'  # \n means newline
>>> s  # without print(), \n is included in the output
'First line.\nSecond line.'
>>> print(s)  # with print(), \n produces a new line
First line.
Second line.

>>> text = ('Put several strings within parentheses '
...         'to have them joined together.')
>>> text
'Put several strings within parentheses to have them joined together.' #string output

>>> s = 'supercalifragilisticexpialidocious'
>>> len(s)   #to find length of string s

Integers (int) and floats (float) in Python

Integers in Python are numbers that do not have a decimal point in them. Floats in Python are numbers that have a decimal point in them. The example below illustrates the basics of integers and floats in Python:

# Basics of integers and floats from input and output console example

>>> 2 + 2    #simple addition
>>> 50 - 5*6    #arithmetic operation
>>> (50 - 5*6) / 4  #arithmetic operation
>>> 8 / 5  # division always returns a floating point number
>>> 17 / 3  # classic division returns a float
>>> 17 // 3  # floor division discards the fractional part
>>> 17 % 3  # the % operator returns the remainder of the division
>>> 5 * 3 + 2  # result * divisor + remainder
>>> 5 ** 2  # 5 squared
>>> 2 ** 7  # 2 to the power of 7
>>> width = 20
>>> height = 5 * 9
>>> width * height

Lists (list) in Python

Lists in Python are array sequences that store the collection of the same or different data types. The elements of a list are surrounded by square brackets, i.e, [ ]. The example below illustrates the basics of lists in Python:

# Basics of lists from I/O console example

>>> squares = [1, 4, 9, 16, 25] #defining the list
>>> squares
[1, 4, 9, 16, 25]               #showing list

>>> squares[0]  # indexing returns the item
>>> squares[-1]
>>> squares[-3:]  # slicing returns a new list
[9, 16, 25]

>>> squares[:] # returns all items
[1, 4, 9, 16, 25]

>>> cubes = [1, 8, 27, 65, 125] # another list
>>> cubes[3] = 64  # replace an element
>>> cubes
[1, 8, 27, 64, 125]

>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] # another list
>>> letters
['a', 'b', 'c', 'd', 'e', 'f', 'g']

>>> letters[2:5] = ['C', 'D', 'E'] # replace some values
>>> letters
['a', 'b', 'C', 'D', 'E', 'f', 'g']
>>> letters[2:5] = [] # remove some values
>>> letters
['a', 'b', 'f', 'g']

>>> letters[:] = [] # clear the list by replacing all the elements with an empty list
>>> letters

>>> letters = ['a', 'b', 'c', 'd'] # another list
>>> len(letters) # gives length of list

Tuples (tuples) in Python

Tuples in Python are array sequences that store the collection of the same or different data types. The elements of a tuple are surrounded by round brackets, i.e, ( ). Unlike lists, the elements of a tuple cannot be changed. The example below illustrates the basics of tuples in Python:

# Basics of tuples from I/O console example

>>> squares = (1, 4, 9, 16, 25) # defining the tuple
>>> squares
(1, 4, 9, 16, 25)               # showing tuple

>>> squares[0]  # indexing returns the item
>>> squares[-1]
>>> squares[-3:]  # slicing returns a new tuple
(9, 16, 25)

>>> squares[:] # returns all items
(1, 4, 9, 16, 25)

>>> letters = ('a', 'b', 'c', 'd') # another tuple
>>> len(letters) # gives length of tuple

# Unlike lists, the elements of a tuple cannot be changed.

>>> cubes = (1, 8, 27, 65, 125) # another tuple
>>> cubes[3] = 64  # replace an element
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

Dictionary (dict) in Python

Dictionary in Python is just a set of key-value pairs, with the requirement that the keys are unique (within one dictionary). The elements of a dictionary are surrounded by curly brackets, i.e, { }. The example below illustrates the basics of dictionaries in Python:

# Basics of dictionary from I/O console example

# Defining a dictionary
>>> costs_dict = {'Kitkat':1300, 'Unicorn':1800, 'Chocolateroll':1000, 'Barbiedoll':3600, 'MickeyMouse':3600, 'Doraemon':1800} 
>>> costs_dict
{'Kitkat': 1300, 'Unicorn': 1800, 'Chocolateroll': 1000, 'Barbiedoll': 3600, 'MickeyMouse': 3600, 'Doraemon': 1800}

# Print value from given key
>>> cost_doraemon_cake = costs_dict['Doraemon'] 
>>> cost_doraemon_cake 

# Insert new key value pair
>>> costs_dict['PeppaPig ']=1800
>>> costs_dict
{'Kitkat': 1300, 'Unicorn': 1800, 'Chocolateroll': 1000, 'Barbiedoll': 3600, 'MickeyMouse': 3600, 'Doraemon': 1800, 'PeppaPig ': 1800}

# Remove key value pair
>>> del costs_dict['Doraemon']
>>> costs_dict
{'Kitkat': 1300, 'Unicorn': 1800, 'Chocolateroll': 1000, 'Barbiedoll': 3600, 'MickeyMouse': 3600, 'PeppaPig ': 1800}

# Convert the key to list
>>> cake_items = list(costs_dict)
>>> cake_items
['Kitkat', 'Unicorn', 'Chocolateroll', 'Barbiedoll', 'MickeyMouse', 'PeppaPig ']

Sets (set) in Python

A set in Python consists of unordered collection with no duplicate elements. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference. Curly braces or the set() function can be used to create sets. The example below illustrates the basics of sets in Python:

# Basics of sets from I/O console example

# Defining a set
>>> cake_items = {'kitkat', 'Unicorn', 'Chocolateroll', 'Barbiedoll', 'MickeyMouse','Doraemon'}
>>> cake_items
{'Chocolateroll', 'MickeyMouse', 'kitkat', 'Doraemon', 'Unicorn', 'Barbiedoll'}

# Fast membership testing
>>> 'Doraemon' in cake_items
>>> 'Ogge' in cake_items

# Demonstrate set operations on unique letters from two words
>>> a = set('aezakmi')
>>> a
{'z', 'i', 'k', 'm', 'e', 'a'}

>>> b = set('alacazam')
>>> b
{'z', 'l', 'm', 'c', 'a'}

# Print both sets
>>> print("a,b:",a,b)
a,b: {'z', 'i', 'k', 'm', 'e', 'a'} {'z', 'l', 'm', 'c', 'a'} 

# Letters in a but not in b
>>> print("a-b:",a-b)
a-b: {'k', 'e', 'i'}

# Letters in a or b or both
>>> print("a|b:",a|b)
a|b: {'z', 'i', 'l', 'k', 'm', 'e', 'c', 'a'}

# Letters in both a and b
>>> print("a&b:",a&b)
a&b: {'a', 'm', 'z'}

# Letters in a or b but not both
>>> print("a^b:",a^b)
a^b: {'l', 'k', 'e', 'c', 'i'}

type() function in Python

You can find the data type of any object by using the type() function in Python.

# Example of type() function

>>> type("Apple")
<class 'str'>

>>> type(2.4)
<class 'float'>

>>> type({'asd','ert'})
<class 'set'>

Comments in Python

Comments are basically a programmer-readable explanation or annotation in the source code of a computer program and are generally ignored by compilers and interpreters. Types of comments used in Python are:

  • Single Line Comment – Single line comments in Python begin with a hash mark (#) and whitespace character and continue to the end of the line.
# Basics of single line comment from I/O console example

# The line below prints “Hello, World!” to console 
>>> print("Hello, World!") 
Hello, World!
  • Multiline comment/Block Comments – Usually, a multiline string can be wrapped as a whole comment inside a set of triple quotes (”’) for block comments.
# Basics of multiline comment from I/O console example

 The code below takes an input from user with message:"Enter your User name:"
 Suppose user entered "smith"
 After user Enters the name it gives out message:"Hello, smith"

# Getting a user input
>>> user_input = input()

# Printing the user input
>>> print("Hello, ", user_input)
Hello, John

That is it for data types and operations in Python. Head onto the next chapter on Control Flow Tools in Python.

Chapter III: Control Flow Tools in Python

In this chapter, you will learn the various control flow tools used in Python.

If statement

If statements are responsible for executing programming blocks based on specified conditions.

# Example of if, elif and else statement 

# Program to find whether a given integer is positive, negative or zero

x = int(input("Please enter an integer: "))

if x < 0: 
    print('Negative Number')   
elif x == 0:
elif x > 1:
    print('Positive Number')
    print('None') #This is optional here
Please enter an integer: -9
Negative Number

For statement

Python’s for statement iterates over the items of any sequence (a list or a string) in the order that they appear in the sequence. It differs a bit from what you may be used to in other programming languages such as C or C++.

Example of for statement in Python:

# Program that iterates over a given list of numbers
list_of_numbers = [10, 15, 20, 25, 30, 35]

# for statement
for number in list_of_numbers:

range() function

The range() function generates an arithmetic progression. If you do need to iterate over a sequence of numbers, the built-in range() function comes in handy.

Format: range(a,b,c)


a starting value that is inclusive
b ending value that is exclusive
c step used in progression (optional)

Example of range() function in Python:

# For statement with range() function

for x in range(10,40,5): # Starting number is with 10 included, ending value is 39, step is 5


While statement

The While statement is used to execute a block of statements while some specified condition is matched.

Example of while statement in Python:

# Declaring a variable x
x = 10

while x < 35:  # continue loop while x is less than 35
    x = x + 5

Break and Continue statement

Break and continue statements alter the flow of a normal loop. The break statement breaks out of the innermost enclosing for or while loop, whereas, the continue statement continues with the next iteration of the loop i.e. it escapes the block of the statement below it.

Example of break and continue statement in Python:

# Defining a list of elements
actions = ["wake", "wash", "eat", "work", "play", "sleep"]

for action in actions:
    if action=="sleep":
        break            # if the action is sleep, this would terminate the loop completely
    elif action=="play":
        continue        # if the action is play, this would not terminate the loop but continues with next iteration 

Pass statement

The pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action.

#Example of pass statement

x = 5
if x == 5:
    pass     # this just passes does nothing

That is it for control flow tools in Python. Head onto the next chapter on Input and Output Operation in Python.

Chapter IV: Input and Output Operation in Python

In this chapter, you will learn the input and output operation in Python.

In python, the basic input-output operations can be carried out using the input() function and print() function respectively as illustrated in the example below:

# Basics of input and output from I/O console example

# Getting a user input
>>> user_input = input()

# Printing the user input
>>> print("Hello, ", user_input)
Hello, John

The example below shows some output formatting:

value = 1015
quantity = 'Pressure'

# Using format() method [NEW]
print('The {} is {}{}'.format(quantity, value,unit))

# Using % format [OLD]
import math
print('The value of pi is approximately %5.3f.' % math.pi)
The Pressure is 1015mBar
The value of pi is approximately 3.142.

Reading and writing files in Python

The open() function returns a file object and is most commonly used with two arguments: open(filename, mode)

f = open(‘workfile’, ‘w’)

f.read(size) reads some quantity of data and returns it as a string (in text mode) or bytes object (in binary mode). Size is an optional numeric argument

f.write(string) writes the contents of string to the file, returning the number of characters written.

# Example of file reading and writing

# Writing to a file(.txt)
with open("test.txt",'w',encoding = 'utf-8') as f:
   f.write("First line\n")
   f.write("Second line\n")
   f.write("Third line\n")

# Reading from a the same file
with open("test.txt",'r') as f:
# Closing the file
First line
Second line
Third line

There you have it! Head onto the next chapter on Errors and Exceptions in Python.

Chapter V: Errors and Exceptions in Python

In this chapter, you will learn the various errors and exceptions in Python. There are two kinds of errors: syntax errors and exceptions.

Syntax Errors

Syntax errors, also known as parsing errors where the parser repeats the offending line and displays a little ‘arrow’ pointing at the earliest point in the line where the error was detected.

>>while True print('Hello world') 
File "", line 1
    while True print('Hello world')
SyntaxError: invalid syntax 


Even if a statement or expression is syntactically correct, it may cause an error when an attempt is made to execute it.These errors detected during execution are called exceptions.

>>10 * (1/0)
Traceback (most recent call last):
File "", line 1, in 
ZeroDivisionError: division by zero   

try-except statements

We can write programs that handle selected exceptions using try-except statements in Python.

The try-except statement works as follows:

  • First, the try clause (the statement(s) between the try and except keywords) is executed
  • If no exception occurs, the except clause is skipped and execution of the try statement is finished
  • If an exception occurs during the execution of the try clause, the rest of the clause is skipped. Then, if its type matches the exception named after the except keyword, the except clause is executed, and then execution continues after the try statement.
  • If an exception occurs which does not match the exception named in the except clause, it is passed on to outer try statements; if no handler is found, it is an unhandled exception and execution stops with a message as shown above.
# Simple example of handling value error exception

while True:
        x = int(input("Please enter a number: "))
    except ValueError:
        print("Oops!  That was no valid number.  Try again...")
Please enter a number: dsa
Oops!  That was no valid number.  Try again...
Please enter a number: 5

That is it on errors and exceptions in Python. Head onto the next chapter on Classes and Objects in Python.

Chapter VI: Classes and Objects in Python

In this chapter, you will learn about classes and objects in Python.

Classes and Objects

Python is an object-oriented programming language. Python focuses on entities known as objects unlike functions in procedure-oriented programming languages. An object is a collection of data(variables) and methods(functions). Similarly, a class can be understood as the “blueprint” for creating objects.

A class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to it for maintaining its state. Class instances can also have methods for modifying its state.

Defining a Class in Python

In python, a class can be defined by using the keyword class. The simplest form of class definition looks like this:

 class ClassName:

The following example illustrates a class that has an attribute(variable) x and a method(function) demoMethod:

class DemoClass:
    x = 0 # Attribute
    def demoMethod(self): # Method
        print('Method successfully called')

Creating an Object in Python

Now, objects can be instantiated from a class already defined. The general syntax for creating an object from a class is:

>>> objectName = ClassName()

An object can be instantiated from the DemoClass created earlier. Then, we can access the attribute (x) as well as call the method demoMethod as shown below:

# Instantiating an object
>>> obj1 = DemoClass()

# Accessing the attribute
>>> print(obj1.x) 

# Calling the method(function)
>>> obj1.demoMethod() 
'Method successfully called'

The __init__() Method

All classes create objects, and all objects contain characteristics called attributes. We use the __init__() method to initialize (specify) an object’s initial attributes by giving them their default value (or state). Finally, the objects are created by instantiating the class.

The following example illustrates the use of the __init__() method:

#Simple class implementation in python

class MyClass(object):
    def __init__(self,val):
        self.value = val
    def value_show(self):
        print("The value of my class is",self.value)

my_class_object1 = MyClass(365)
my_class_object2 = MyClass(48)


# Printing the address of the object
The value of my class is 365
The value of my class is 48
<__main__.Myclass object at 0x000001F0C57050F0>

From the above example, we can also see that the value of attributes differs for each object in a class. In other words, each object has its own values of the attributes defined in the class definition.

Scopes and Namespaces

A namespace is a system to have a unique name for each and every object in Python. Scope refers to the coding region from which a particular Python object is accessible. The example below illustrates this:

# An example of Scopes and Namespaces 
def scope_test():
    def do_local():
        spam = "local spam"

    def do_nonlocal():
        nonlocal spam
        spam = "nonlocal spam"

    def do_global():
        global spam
        spam = "global spam"

    spam = "test spam"
    print("After local assignment:", spam)
    print("After nonlocal assignment:", spam)
    print("After global assignment:", spam)

print("In global scope:", spam)

After local assignment: test spam
After nonlocal assignment: nonlocal spam
After global assignment: nonlocal spam
In global scope: global spam

That is it for classes and objects in Python. Head onto the next chapter on Standard Libraries in Python.

Chapter VII: Standard Libraries in Python

In this chapter, you will get a basic overview of the standard libraries in Python.

The Python Standard Library is a collection of script modules accessible to a Python program to simplify the programming process and removing the need to rewrite commonly used commands. They can be used by ‘calling/importing’ them at the beginning of a script. Generally, these standard libraries are installed alongside Python by Python installers.

Refer to the official documentation to get a list of all the standard libraries python offer.

Some Important Standard Libraries in Python

  • os module provides dozens of functions for interacting with the operating system.
  • shutil module provides a higher-level interface on files and collections of files that is easier to use.
  • glob module provides a function for making file lists from directory wildcard searches.
  • argparse module provides a more sophisticated mechanism to process command-line arguments.
  • re module provides regular expression tools for advanced string processing. For complex matching and manipulation, regular expressions offer succinct, optimized solutions.
  • math module gives access to the underlying C library functions for floating-point math.
  • random module provides tools for making random selections.
  • statistics module calculates basic statistical properties (the mean, median, variance, etc.) of numeric data.
  • datetime module supplies classes for manipulating dates and times in both simple and complex ways.
  • Common data archiving and compression formats are directly supported by modules including: zlib, gzip, bz2, lzma, zipfile and tarfile.
  • timeit module quickly demonstrates a modest performance advantage.
  • doctest module provides a tool for scanning a module and validating tests embedded in a program’s docstrings.
  • unittest module is not as effortless as the doctest module, but it allows a more comprehensive set of tests to be maintained in a separate file.
  • reprlib module provides a version of repr() customized for abbreviated displays of large or deeply nested containers.
  • pprint module offers more sophisticated control over printing both built-in and user-defined objects in a way that is readable by the interpreter.
  • textwrap module formats paragraphs of text to fit a given screen width.
  • threading module can run tasks in the background while the main program continues to run.
  • decimal module offers a Decimal datatype for decimal floating-point arithmetic.

That is it for standard libraries in Python. Head onto the final chapter on Virtual Environments and Packages in Python.

Chapter VIII: Virtual Environments and Packages in Python

Python applications most often require packages and modules that don’t come as part of the standard library. There are cases when applications need a specific version of a library since the application may be written using a specific version of the library. So it is not possible for one Python installation to meet the requirements of every application.

The solution for this problem is to create a virtual environment, a self-contained directory tree that contains a Python installation for a particular version of Python, plus a number of additional packages. With these, different applications can then use different virtual environments as per requirement.

Creating Virtual Environments

To create a virtual environment, decide upon a directory where you want to place it, navigate to that directory from command line/terminal and run the venv module as:

python3 -m venv myenv

This will create the myenv directory if it doesn’t exist, and also create directories inside it containing a copy of the Python interpreter, the standard library, and various supporting files. A common directory location for a virtual environment is .venv.

Directory Tree Of an Environment

project-directory/myvenv/                  # Environment's root directory
├── bin
│   ├── activate                           # Scripts to activate the virtual environment
│   ├── activate.csh                       
│   ├── activate.fish                     
│   ├── easy_install
│   ├── easy_install-3.7
│   ├── pip
│   ├── pip3
│   ├── pip3.7
│   ├── python -> /usr/local/bin/python    # Symlinks to system-wide
│   └── python3 -> python3.8               # Python instances.
├── include
├── lib
│   └── python3.8
│       └── site-packages                  # Stores local site packages
└── pyvenv.cfg

Activating the Virtual Environment

Once you’ve created a virtual environment, you may activate it. After activation of a virtual environment, every python code you run will use the python interpreter of this environment.

For Windows, run:


For Unix or MacOS, run:

source myenv/bin/activate

Managing Packages

You can install, upgrade, and remove packages using a program called pip which is a package manager for python. By default, pip will install packages from the Python Package Index, https://pypi.org.

The program manager pip has a number of subcommands: “search”, “install”, “uninstall”, “freeze”, etc. You can install the latest version of a package by specifying a package’s name.

pip install package_name

For example, package_name can be any package known by pypi such as numpy, pandas, matplotlib, etc. So, to install numpy, the following command can be used:

pip install numpy

Conversely, you can uninstall the package as:

pip uninstall package_name

Requirements File

A requirements file lists all the external packages/modules and their version number that are installed in a particular virtual environment. Requirements file comes handy when we need to replicate a virtual environment in some other computer(s) so that an application runs perfectly on the other computer(s) too.

To generate a requirements file of an environment, run the following command when that environment is activated:

pip freeze > requirements.txt

After running this command, a new file named requirements.txt will be created that lists all the modules installed in that environment.

Now, on another environment, all the packages listed on the requirements.txt can be installed by running the following command:

pip install -r requirements.txt

With this, we have come to the end of our Python Course.

Request Quote

Please fill in the form below and we'll get in touch with you.