Introduction To Python Programming
How to Use Self-Learning Material?
The pedagogy used to design this course is to enable the student to assimilate the concepts
with ease. The course is divided into modules. Each module is categorically divided into units or
chapters. Each unit has the following elements:
Table of Contents: Each unit has a well-defined table of contents. For example: “1.1.1.
(a)” should be read as “Module 1. Unit 1. Topic 1. (Sub-topic a)” and 1.2.3. (iii) should
be read as “Module 1. Unit 2. Topic 3. (Sub-topic iii).
Aim: It refers to the overall goal that can be achieved by going through the unit.
Instructional Objectives: These are behavioural objectives that describe intended
learning and define what the unit intends to deliver.
Learning Outcomes: These are demonstrations of the learner’s skills and experience
sequences in learning, and refer to what you will be able to accomplish after going
through the unit.
Self-Assessment Questions: These include a set of multiple-choice questions to be
answered at the end of each topic.
Did You Know?: You will learn some interesting facts about a topic that will help you
improve your knowledge. A unit can also contain Quiz, Case Study, Critical Learning
Exercises, etc., as metacognitive scaffold for learning.
Summary: This includes brief statements or restatements of the main points of unit
and summing up of the knowledge chunks in the unit.
Activity: It actively involves you through various assignments related to direct
application of the knowledge gained from the unit. Activities can be both online and
offline.
Bibliography: This is a list of books and articles written by a particular author on a
particular subject referring to the unit’s content.
e-References: This is a list of online resources, including academic e-Books and
journal articles that provide reliable and accurate information on any topic.
Video Links: It has links to online videos that help you understand concepts from a
variety of online resources.
Introduction To Python Programming
LEADERSHIP KLEF
Er. Koneru Satyanarayana Dr. G. Pardha Saradhi Varma
President Vice Chancellor
Dr. N. Venkatram Dr. K. Subbarao
Pro-Vice Chancellor Incharge Registrar
Introduction To Python Programming
CREDITS
Author
Dr. A. Sivaramakrishnan
Director CDOE
C. Shanath Kumar
Instructional Designer
Nabina Das
Project Manager
K. D. N. Lakshmi
Graphic Designer
J. Srinivasa Reddy
Introduction To Python Programming
First Edition, 2023.
KL Deemed to be University-CDOE has full copyright over this educational material. No
part of this document may be produced, stored in a retrieval system, or transmitted, in any
form or by any means.
Introduction To Python Programming
Author’s Profile
Dr. A. Sivaramakrishnan
Associate Professor
Dr. A. Sivaramakrishnan completed his Ph.D in Computer Science from VELS University, in April
2015, Chennai, Tamil Nadu, India. Currently, he is an Associate Professor of Computer Science
and Applications at KL (Deemed to be) University, Vijayawada, India. He graduated in Computer
Science from Bharathiar University, Coimbatore. He pursued a Master of Computer Applications
from the M.I.E.T, Bharathidasan University, Trichy and did a Master of Philosophy in Computer
Science from Madurai Kamaraj University, Madurai. With exposure to Digital Image Processing,
he has 15+ years of teaching and industry experience. Dr. Sivaramakrishnan has published in
many international research journals and he has worked abroad for more than three years.
Introduction To Python Programming
Introduction to Python Programming
Course Description
Introduction to programming basics (what it is and how it works), binary computation, problem-
solving methods and algorithm development. Includes procedural and data abstractions, program
design, debugging, testing, and documentation. Covers data types, control structures, functions,
parameterpassing, library functions, arrays, inheritance and object oriented design. Laboratory
exercises in Python.
Introduction To Python Programming 6
This course is Divided into Four Modules.
MODULE 1: Introduction to Python Programming
Need for programming, Programming languages, History of python, Python Installation, Interactive
modes, keywords, variables, Identifiers, data types –Numbers, sequences, Sets, Mappings and
None, mutable vs Immutable data types
MODULE 2: Operators in Python
Arithmetic, Assignment, Relational, Logical, Identity and Membership Operators, Expressions,
Precedence of operators in python, Type Conversion – Implicit and Explicit, Functions in
Python, Simple Programs on If, If -else, Nested If and for
MODULE 3: Introduction to Numpy
Numpy Array, Operations on Arrays, Indexing and Slicing; Introduction to Pandas: Series and
Data frames – simple examples.
MODULE 4: Introduction to Data visualization
Matplotlib – Usage of pyplot, pyplot fuctions with examples and Seaborn with simple examples.
7 Introduction To Python Programming
Table of Contents
MODULE 1
Introduction to Python Programming
Unit 1 Introduction to Python
Unit 2 Need for Programming
MODULE 2
Operators, Conditional and Looping in Python
Unit 1 Operators in Python
Unit 2 Functions in Python
MODULE 3
Introduction to Numpy
Unit 1 Numpy Array
Unit 2 Pandas
MODULE 4
Introduction to Data visualization
Unit 1 Introduction to Data visualization
Unit2 Matplotlib, Usage of pyplot
Introduction To Python Programming 8
INTRODUCTION TO PYTHON PROGRAMMING
Module 1
Introduction to Python
9 Introduction To Python Programming
Module 1
Module Description
Programming helps in speeding up the input and output processes in a machine. It is important
to automate, collect, manage, calculate, and analyze the processing of data and information
accurately. Programming helps create software and applications that help computer and mobile
users in daily life.
In this module we are going to see the importance of programming and introduction about the
Python Programming, installation of Python programming and basic python commands and how
to built the python programming
This Module is divided into the following units:
Unit 1.1 Introduction to Python
Unit 1.2 Need for Programming
Introduction To Python Programming 10
INTRODUCTION TO PYTHON PROGRAMMING
Module 1
Introduction to Python Programming
Unit 1
Introduction to Python
11 Introduction To Python Programming
Unit Table of Contents
Unit 1 Introduction to Python
Aim _____________________________________________________12
Instructional Objectives _____________________________________12
Learning Outcomes_________________________________________12
1.1 Introduction ____________________________________________13
1.1.1 Introduction to Python________________________________14
1.1.2 Need for programming _______________________________15
Summary _________________________________________________18
Glossary__________________________________________________18
Bibliography_______________________________________________19
e-References______________________________________________19
Introduction To Python Programming 12
Aim
To introduce students to the basic concepts of programming
Familiarise students with Programming such as Python Programming,
functions, and the importance of programming in today’sworld
Instructional Objectives
To make you enthusiastic about learning of Python Programming
fundamentals
● Demonstrate why programming are important components in various indus-
tries
● Describe the widespread use of Programming in education, business, and
other fields like Data Science, Web Development, Artificial Intelligence.
● Explain to you the Installation of Python on our computer.
● Discuss the basic commands and programs use in the real world
Learning Outcomes
Upon completion of this unit, you will be able to:
● Define a computer programming and its importance
● Understand and use the basic python commands
● Able to install Python Programming
● Identify the basic components and applications of a python Programming
13 Introduction To Python Programming
1.1 Introduction
Python is an interpreted, object-oriented, high-level programming language with dynamic seman-
tics. Its high-level built in data structures, combined with dynamic typing and dynamic binding,
make it very attractive for Rapid Application Development, as well as for use as a scripting or glue
language to connect existing components together.
1.1.1 Introduction to Python
Python is a high-level, general-purpose and a very popular programming language. Python
programming language (latest Python 3) is being used in web development, Machine Learning
applications, along with all cutting edge technology in Software Industry. Python Programming
Language is very well suited for Beginners, also for experienced programmers with other pro-
gramming languages like C++ and Java.
Facts about Python Programming Language:
1. Python is currently the most widely used multi-purpose, high-level programming language.
2. Python allows programming in Object-Oriented and Procedural paradigms.
3. Python programs generally are smaller than other programming languages like Java. Pro-
grammers must type relatively less and indentation requirement of the language, makes
them readable all the time.
4. Python language is being used by almost all tech-giant companies like – Google, Ama-
zon, Facebook, Instagram, Dropbox, Uber… etc.
5. The biggest strength of Python is huge collection of standard library which can be
used for the following:
● Machine Learning
● GUI Applications (like Kivy, Tkinter, PyQt etc. )
● Web frameworks like Django (used by YouTube, Instagram, Dropbox)
● Image processing (like OpenCV, Pillow)
● Web scraping (like Scrapy, BeautifulSoup, Selenium)
● Test frameworks
● Multimedia
● Scientific computing
Introduction To Python Programming 14
1.1.2 Need for programming
Programming is using a language that a machine can understand in order to get it to perform var-
ious tasks. Computer programming is how we communicate with machines in a way that makes
them function how we need.
What is a Program?
A program is a group of logical, mathematical, and sequential functions grouped together. When
they are grouped, these functions perform a task. Each programming language focuses on differ-
ent types of tasks as well as gives commands to the machine in different ways.
Why are Programming Languages Needed?
Programming language is also named as high-level languages. Some of the commonly used
languages are- C, C++, Java, JavaScript, React JS, PHP, .Net, etc. The mobile applications are
coded by using different languages having distinct features. However, programming languages
share a lot of similarities with each other.
To advance your ability to develop real algorithms- Most of the languages come with a lot of fea-
tures for the Programmers. They can be used in a proper way to get the best results.
To Improve Customization of Your Current Coding- By using basic features of the existing pro-
gramming language you can simplify things to program a better option to write resourceful codes.
There is no compulsion of writing code in a specific way. The thing which matters is the usage of
features used and clarity of the concept.
To Increase Your Vocabulary Of beneficial Programming Constructs- Programmers use high-lev-
el languages to express thoughts. And, by using the best features they can easily explain the
working of a specific application, device, etc.
Types of programming language
1.Low-level programming language
Low-level language is machine-dependent (0s and 1s) programming language. The processor
runs low- level programs directly without the need of a compiler or interpreter, so the programs
written in low- level language can be run very fast.
15 Introduction To Python Programming
Low-level language is further divided into two parts -
i. Machine Language
Machine language is a type of low-level programming language. It is also called as ma-
chine code or object code. Machine language is easier to read because it is normally
displayed in binary or hexadecimal form (base 16) form. It does not require a translator
to convert the programs because computers directly understand the machine language
programs.
The advantage of machine language is that it helps the programmer to execute the pro-
grams faster than the high-level programming language.
ii. Assembly Language
Assembly language (ASM) is also a type of low-level programming language that is de-
signed for specific processors. It represents the set of instructions in a symbolic and
human-understandable form. It uses an assembler to convert the assembly language to
machine language.
The advantage of assembly language is that it requires less memory and less execution
time to execute a program.
2. High-level programming language
High-level programming language (HLL) is designed for developing user-friendly software pro-
grams and websites. This programming language requires a compiler or interpreter to translate
the program into machine language (execute the program).
The main advantage of a high-level language is that it is easy to read, write, and maintain.
High-level programming language includes Python, Java, JavaScript, PHP, C#, C++, Objective
C, Cobol, Perl, Pascal, LISP, FORTRAN, and Swift programming language.
A high-level language is further divided into three parts
i. Procedural Oriented programming language
Procedural Oriented Programming (POP) language is derived from structured program-
ming and based upon the procedure call concept. It divides a program into small proce-
dures called routines or functions.
Introduction To Python Programming 16
Procedural Oriented programming language is used by a software programmer to create a pro-
gram that can be accomplished by using a programming editor like IDE, Adobe Dreamweaver, or
Microsoft Visual Studio
Example: C, FORTRAN, Basic, Pascal, etc.
ii. Object-Oriented Programming language
Object-Oriented Programming (OOP) language is based upon the objects. In this pro-
gramming language, programs are divided into small parts called objects. It is used to im-
plement real-world entities like inheritance, polymorphism, abstraction, etc in the program
to makes the program reusable, efficient, and easy-to-use.
The main advantage of object-oriented programming is that OOP is faster and easier to
execute, maintain, modify, as well as debug.
Example: C++, Java, Python, C#, etc.
iii. Natural language
Natural language is a part of human languages such as English, Russian, German, and
Japanese. It is used by machines to understand, manipulate, and interpret human’s lan-
guage. It is used by developers to perform tasks such as translation, automatic summari-
zation, Named Entity Recognition (NER), relationship extraction, and topic segmentation.
The main advantage of natural language is that it helps users to ask questions in any
subject and directly respond within seconds.
17 Introduction To Python Programming
Summary
● Python is an interpreted, object-oriented, high-level programming language with
dynamic semantics.
● Its high-level built in data structures, combined with dynamic typing and dynamic
binding, make it very attractive for Rapid Application Development, as well as
for use as a scripting or glue language to connect existing components together.
● Python’s simple, easy to learn syntax emphasizes readability and therefore re-
duces the cost of program maintenance.
● Python supports modules and packages, which encourages program modularity
and code reuse. The Python interpreter and the extensive standard library are
available in source or binary form without charge for all major platforms, and can
be freely distributed.
Glossary
● Aproblem solving: The process of formulating a problem, evaluating different
options, and expressing a solution.
● Aalgorithm: A general step by step process for solving a problem.
● The process of performing a series of instructions written in the program
code. Also called “run.”
● constant: Fixed values, either numbers, letters or strings, that do not change.
Introduction To Python Programming 18
Bibliography
1. Python: The Complete Reference Paperback – 20 March 2018 by Martin C.
Brown (Author)
2. Python Programming: Using Problem Solving Approach By Reema Thareja
(Author)
3. Python Crash Course: A Hands-On, Project-Based Introduction to Program-
ming by Eric Matthes
e-References
● https://www.amazon.in/Basic-Core-Python-Programming-Applica-
tions-ebook/dp/B0933F73LK
● https://slideplayer.com/slide/13549208/#.Y6AeQ1THs4I.gmail
● https://docs.python.org/3/whatsnew/3.11.html
19 Introduction To Python Programming
INTRODUCTION TO PYTHON PROGRAMMING
Module 1
Introduction to python programming
Unit 2
History of Python Programming
Introduction To Python Programming 20
Unit Table of Contents
Unit 2 History of Python Programming
Aim ____________________________________________________________22
Instructional Objectives ____________________________________________22
Learning Outcomes _______________________________________________22
1.2. History of Python Programming Python History and Versions ___________23
1.2.1 Python Installation ________________________________________24
1.3.1 Python Keywords_________________________________________27
1.3.2. Python Numbers _________________________________________29
1.3.3 Mutable vs. Immutable Objects _______________________________31
Self-Assessment Questions _________________________________________33
Answer Keys_____________________________________________________35
Bibliography _____________________________________________________36
e-References ____________________________________________________36
21 Introduction To Python Programming
Aim
To introduce students to the basic concepts of programming
Familiarise students with Programming such as Python Programming,
functions, and the importance of programming in today’sworld
Instructional Objectives
To make you enthusiastic about learning of Python Programming
fundamentals
● Demonstrate why programming are important components in various indus-
tries
● Describe the widespread use of Programming in education, business, and
other fields like Data Science, Web Development, Artificial Intelligence.
● Explain to you the Installation of Python on our computer.
● Discuss the basic commands and programs use in the real world
Learning Outcomes
Upon completion of this unit, you will be able to:
● Define a computer programming and its importance
● Understand and use the basic python commands
● Able to install Python Programming
● Identify the basic components and applications of a python Programming
Introduction To Python Programming 22
1.2 History of Python Programming Python History and Versions
● Python laid its foundation in the late 1980s.
● The implementation of Python was started in December 1989 by Guido Van Rossum at
CWI in Netherland.
● In February 1991, Guido Van Rossum published the code (labelled version 0.9.0) to alt.
sources.
● In 1994, Python 1.0 was released with new features like lambda, map, filter, and reduce.
● Python 2.0 added new features such as list comprehensions, garbage collection sys-
tems.
● On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was designed to
rectify the fundamental flaw of the language.
● ABC programming language is said to be the predecessor of Python language, which
was capable of Exception Handling and interfacing with the Amoeba Operating System.
● The following programming languages influence Python:
ABC language.
Why the Name Python?
There is a fact behind choosing the name Python
Guido van Rossum was reading the script of a popular BBC comedy series “Monty Python’s Fly-
ing Circus”. It was late on-air 1970s.
Van Rossum wanted to select a name which unique, sort, and little-bit mysterious. So he decided
to select naming Python after the “Monty Python’s Flying Circus” for their newly created program-
ming language.
The comedy series was creative and well random. It talks about everything. Thus it is slow and
unpredictable, which made it very interesting.
Python is also versatile and widely used in every technical field, such as Machine Learning
● Artificial Intelligence
● Web Development, Mobile Application
● Desktop Application, Scientific Calculation, etc.
23 Introduction To Python Programming
1.2.1 Python Installation
How to Install Python (Environment Set-up)
The first step is to learn how to install or update Python on a local machine or computer. Proce-
dure as follows
Installation on Windows
● Visit the link https://www.python.org/downloads/ to download the latest release of
Python
● In this process, we will install Python 3.11.1 on our Windows operating system
● When we click on the above link, it will bring us the following page.
● Step - 1: Select the Python's version to download.
● Click on the download button.
Python releases by version number:
Release version Release date
Python 3.11.1 Dec. 6, 2022 Download
Python 3.10.9 6, 2022 Dec. Download
Python 3.9.16 6, 2022 Dec. Download
Python 3.8.16 6, 2022 Dec. Download
Python 3.7.16 Dec. 6, 2022 Download
Python 3.11.0 Oct. 24, 2022 Download
Python 3.9.15 Oct. 11, 2022 Download
Step - 2: Click on the Install Now
Double-click the executable file, which is downloaded; the following window will open. Select
Customize installation and proceed. Click on the Add Path check box, it will set the Python path
automatically.
Introduction To Python Programming 24
Python 3.11.1 (64-bit) SETUP
Install Python 3.11.1 (64-bit)
Select to install Python with default settings, or choose Customize
to enable or disable features.
Install Now
Install Now C/AUseralu\AppData \ Local\ Programs\
Python\Python311
Includes IDLE, pip and documentation Creates shortcuts and file
associations
Customize installation Choose location and features
Use admin privileges when installing py.exe
Add python.exe to PAT
25 Introduction To Python Programming
Step - 3 Installation in Process
Now, try to run python on the command prompt. Type the command python -version in case of
python3.11.1
Introduction To Python Programming 26
1.3.1 Python Keywords
Brief information on all keywords used in Python.
Keywords are the reserved words in Python. We cannot use a keyword as a variable name,
function name or any other identifier.
Here's a list of all keywords in Python Programming
Keywords in Python programming language
False await else import pass
None break except in raise
True class finally is return
and continue for lambda try
as def from nonlocal while
assert del global not with
osync elif if or yield
Python Variables
Variables are containers for storing data values. Creating Variables
Python has no command for declaring a variable.
A variable is created the moment you first assign a value to it. Example
X=56
Name=”Raju”
Print(x)
Print(y)
Variable Names
A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume). Rules for Python variables:
A variable name must start with a letter or the underscore character
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
Variable names are case-sensitive (age, Age and AGE are three different variables)
name = “James” my_name = “James”
_my_name = “James”
myName = “James”
27 Introduction To Python Programming
MYNAME = “James”
Myname2 = “James”
Print(name)
Print(my_name)
Print(_my_name)
Print(MYNAME)
Print(Myname2)
Output
James
James
James
James
James
James
Introduction To Python Programming 28
1.3.2. Python Numbers
There are three numeric types in Python:
● int
● float
● complex
Variables of numeric types are created when you assign a value to them:
Example
x=5 # int
y = 3.8 # float
z = 2j # complex
To verify the type of any object in Python, use the type() function:
Example
print(type(x))
print(type(y))
print(type(z))
Python Sets
myset = {“apple”, “banana”, “cherry”}
Set
Sets are used to store multiple items in a single variable.
Set is one of 4 built-in data types in Python used to store collections of data, the other 3 are
List, Tuple, and Dictionary, all with different qualities and usage.
A set is a collection which is unordered, unchangeable*, and unindexed.
Duplicates Not Allowed
Sets cannot have two items with the same value.
Example
Duplicate values will be ignored:
newset = {“apple”, “banana”, “cherry”, “apple”}
print(newset)
29 Introduction To Python Programming
Mappings in Python
map() function returns a map object(which is an iterator) of the results after applying the given
function to each item of a given iterable (list, tuple etc.)
Syntax :
map(fun, iter)
Parameters :
fun : It is a function to which map passes each element of given iterable.
iter : It is a iterable which is to be mapped.
Note : You can pass one or more iterable to the map() function.
Returns :
Returns a list of the results after applying the given function to each item of a given iterable (list,
tuple etc.)
Note : The returned value from map() (map object) then can be passed to functions like list() (to
create a list), set() (to create a set) .
CODE 1
# Python program to demonstrate working of map.
# Return double of n def addition(n):
return n + n
# We double all numbers using map()
numbers = (1, 2, 3, 4)
result = map(addition, numbers)
print(list(result))
Output :
[2, 4, 6, 8]
Introduction To Python Programming 30
1.3.3 Mutable vs. Immutable Objects
we can change the contents of a mutable data type in Python, by assigning new values or by
simply adding new values. On contrary to that, we cannot change the contents of an immutable
data type in Python.
Before lining the differences between them, let us first get a short idea about immutable objects
in Python --
In simple words, the value assigned to a variable cannot be changed for the immutable data
types. For example, String is an immutable data type in Python. We cannot change its content,
otherwise, we may fall into a TypeError. Even if we assign any new content to immutable objects,
then a new object is created (instead of the original being modified).
Python handles mutable and immutable objects quite differently. Let us look into the dif-
ference between both of these types of objects:
Python Datatypes
Immutable Datatypes Numbers Strings Tuples
Numbers Lists
Strings Dictionary
Tuples Sets
31 Introduction To Python Programming
Mutable Objects Immutable Objects
A mutable object can be changed after it is An immutable object cannot be changed after
created it is created
Examples : List, Set, Dictionary Exg: tuples, int, float, bool, frozenset.
Mutable objects are not considered as thread Immutable objects are regarded as thread-
safe in nature safe in nature
Immutable objects are faster access when
Mutable Objects are slower to access, as Im-
compared to immutable objects mutable ob-
mutable objects
jects
Immutable objects are best suitable when we
Mutable objects are useful when we need to are sure that we dont need to change them at
Change the size or contentent of our object any point in time
Changing immutable objects is an expensive
operation since it operation in terms of space
Changing mutable objects is a cheaper
and time involves creating a new copy for any
operation in terms of space and time
changes made.
Introduction To Python Programming 32
Self-Assessment Questions
1. Who developed the Python language?
(a) Zim Den
(b) Guido van Rossum
(c) Niene Stom
(d) Wick van Rossum
2. Which one of the following is the correct extension of the Python file?
(a) .py
(b) .python
(c) .p
(d) None of these
3. Which of the following functions is a built-in function in python language?
(a) val()
(b) print()
(c) display()
(d) None of these
4. _____ symbol is used to calculate the power
(a) ^
(b) *
(c) **
(d) None of the above
5. Study the following statement:
>>>”a”+”bc”
What will be the output of this statement?
(a) a+bc
(b) abc
(c) a bc
(d) a
33 Introduction To Python Programming
Self-Assessment Questions
6. Is Python code compiled or interpreted?
(a) Python code is both compiled and interpreted
(b) Python code is neither compiled nor interpreted
(c) Python code is only compiled
(d) Python code is only interpreted
7. What will be the output of the following Python code snippet if x=1?
x<<2
(a) 4
(b) 2
(c) 1
(d) 8
8. Which of the following is true for variable names in Python?
(a) Underscore and ampersand are the only two special characters allowed
(b) Unlimited length
(c) All private members must have leading and trailing underscores
(d) None of these
9. Which of the following is not a core data type in Python programming?
(a) Tuples
(b) Lists
(c) Class
(d) Dictionary
10. What will be the output of the following Python function?
len([“hello”,2, 4, 6])
(a) Error
(b) 6
(c) 4
(d) 3
Introduction To Python Programming 34
Answer Keys
Self-Assessment Questions
Question No. Answers
1 b
2 a
3 b
4 c
5 b
6 a
7 a
8 b
9 c
10 c
35 Introduction To Python Programming
Bibliography
1. Python: The Complete Reference Paperback – 20 March 2018 by Martin C.
Brown (Author)
2. Python Programming: Using Problem Solving Approach By Reema Thareja
(Author)
3. Python Crash Course: A Hands-On, Project-Based Introduction to Program-
ming by Eric Matthes
e-References
● https://www.amazon.in/Basic-Core-Python-Programming-Applica-
tions-ebook/dp/B0933F73LK
● https://slideplayer.com/slide/13549208/#.Y6AeQ1THs4I.gmail
● https://docs.python.org/3/whatsnew/3.11.html
Introduction To Python Programming 36
INTRODUCTION TO PYTHON PROGRAMMING
Module 2
Operators, Conditional and Looping in Python
37 Introduction To Python Programming
Module 2
Module Description
In Python programming, Operators in general are used to perform operations on values and
variables. These are standard symbols used for the purpose of logical and arithmetic operations.
In this module, we will look into different types of Python operators, conditional statements in
Python and looping structures in Python Programming
Operators: These are the special symbols. Eg- + , * , /, etc.
Operand: It is the value on which the operator is applied.
2.1 Operators in Python
2.2 Expressions
2.3 Precedence of operators in python
Introduction To Python Programming 38
INTRODUCTION TO PYTHON PROGRAMMING
Module 2
Unit 1
Operators in Python
39 Introduction To Python Programming
Table of Contents
Unit 2 Operators in Python
Aim _______________________________________________________41
Instructional Objectives _______________________________________41
Learning Outcomes___________________________________________41
Unit 2.1 Operators in Python____________________________________42
2.1.1Type Conversion in Python __________________________48
Bibliography_________________________________________________49
e-References________________________________________________49
40 Introduction To Python Programming
Aim
When student complete operators with Python, they will be able to: Build basic pro-
grams using all operators, conditional logic, looping, and functions.
Work with user input to create interactive programs.
Instructional Objectives
To learn more about python programming students can enrich their knowl-
edge in the following areas
● Able to do coding in Python Operators
● Able to do coding in conditional statements in Python
● Able to perform looping construction is python
Learning Outcomes
Upon completion of this unit, you will be able to:
● Describe the purpose of an operator
● List the different categories of operators
● Describe the concept of operator precedence
● Describing the concept of conditional statements and looping
41 Introduction To Python Programming
2.1 Python Operators
Operators are used to perform operations on variables and values.
In the example below, we use the + operator to add together two values:
print(12 + 5)
Python divides the operators in the following groups:
● Arithmetic operators
● Assignment operators
● Comparison operators
● Logical operators
● Identity operators
● Membership operators
● Bitwise operators
Introduction To Python Programming 42
Python Arithmetic Operators
Arithmetic operators are used with numeric values to perform common mathematical opera-
tions:
Operator Name Example
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
Python Assignment Operators
Assignment operators are used to assign values to variables:
Operator Example Same As
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
Operator Name Example
== Equal x == y
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y
43 Introduction To Python Programming
Python Comparison Operators
Comparison operators are used to compare two values:
Python Logical Operators
Logical operators are used to combine conditional statements:
Operator Description Example
and Returns True if both statements are true x < 5 and x < 10
or Returns True if one of the statements is true x < 5 or x < 4
not Reverse the result, returns False if the result is true not(x < 5 and x < 10)
Python Identity Operators
Identity operators are used to compare the objects, not if they are equal, but if they are
actually the same object, with the same memory location:
Operator Description Example
is Returns True if both variables are the same object x is y
is not Returns True if both variables are not the same object x is not y
Python Membership Operators
Membership operators are used to test if a sequence is presented in an object:
Operator Description Example
in Returns True if a sequence with the specified value is present in the object x in y
Returns True if a sequence with the specified value is not present x not in y
not in
in the object
Introduction To Python Programming 44
Python Bitwise Operators
Bitwise operators are used to compare (binary) numbers:
Operator Name Description
& AND Sets each bit to 1 if both bits are 1
| OR Sets each bit to 1 if one of two bits is 1
^ XOR Sets each bit to 1 if only one of two bits is 1
~ NOT Inverts all the bits
Shift left by pushing zeros in from the right and let the leftmost
<< Zero fill left shift
bits fall off
Signed right Shift right by pushing copies of the leftmost bit in from the left,
>>
shift and let the rightmost bits fall off
Precedence and Associativity of Operators in Python
In this tutorial, you’ll learn how precedence and associativity of operators affect the order of
operations in Python.
Precedence of Python Operators
The combination of values, variables, operators, and function calls is termed as an expression.
The Python interpreter can evaluate a valid expression.
For example:
>>> 5 - 7
-2
Here 5 - 7 is an expression. There can be more than one operator in an expression.
To evaluate these types of expressions there is a rule of precedence in Python. It guides the order
in which these operations are carried out.
For example, multiplication has higher precedence than subtraction.
# Multiplication has higher precedence
# than subtraction
>>> 10 - 4 * 2
2
But we can change this order using parentheses () as it has higher precedence than multiplica-
tion.
45 Introduction To Python Programming
Operators Meaning
() Parentheses
** Exponent
+x, -x, ~x Unary plus, Unary minus, Bitwise NOT
*, /, //, % Multiplication, Division, Floor division, Modulus
+, - Addition, Subtraction
<<, >> Bitwise shift operators
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
==, !=, >, >=, <, <=, is, is not, in, Comparisons, Identity, Membership operators
not in
not Logical NOT
and Logical AND
or Logical OR
# Parentheses () has higher precedence
>>> (10 - 4) * 2
12
The operator precedence in Python is listed in the following table. It is in descending order (up-
per group has higher precedence than the lower ones).
Let’s look at some examples:
Suppose we’re constructing an if...else block which runs if when lunch is either fruit or sandwich
and only if money is more than or equal to 2.
Let’s look at some examples:
Suppose we’re constructing an if...else block which runs if when lunch is either fruit or sandwich
and only if money is more than or equal to 2.
# Precedence of or & and
meal = “fruit”
money = 0
if meal == “fruit” or meal == “sandwich” and money >= 2:
print(“Lunch being delivered”)
else:
print(“Can’t deliver lunch”)
Output
Lunch being delivered
Introduction To Python Programming 46
2.1.1 Type Conversion in Python
Python defines type conversion functions to directly convert one data type to another which is
useful in day-to-day and competitive programming. This article is aimed at providing information
about certain conversion functions.
There are two types of Type Conversion in Python:
● Implicit Type Conversion
● Explicit Type Conversion
Example
x = 20
print(“x is of type:”,type(x))
y = 10.6
print(“y is of type:”,type(y))
z=x+y
print(z)
print(“z is of type:”,type(z))
Output:
x is of type: <class ‘int’>
y is of type: <class ‘float’>
30.6
z is of type: <class ‘float’>
As we can see the data type of ‘z’ got automatically changed to the “float” type while one variable
x is of integer type while the other variable y is of float type. The reason for the float value not be-
ing converted into an integer instead is due to type promotion that allows performing operations
by converting data into a wider-sized data type without any loss of information. This is a simple
case of Implicit type conversion in python.
47 Introduction To Python Programming
Explicit Type Conversion
In Explicit Type Conversion in Python, the data type is manually changed by the user as per their
requirement. With explicit type conversion, there is a risk of data loss since we are forcing an
expression to be changed in some specific data type. Various forms of explicit type conversion
are explained below
1. int(a, base): This function converts any data type to integer. ‘Base’ specifies the base in which
string is if the data type is a string.
2. float(): This function is used to convert any data type to a floating-point number.
Python Functions
A function is a block of code which only runs when it is called.
You can pass data, known as parameters, into a function.
A function can return data as a result.
Creating a Function
In Python a function is defined using the def keyword:
def my_function():
print(“Welcome to my home”)
Calling a Function
To call a function, use the function name followed by parenthesis:
def my_function():
print(“Hello from a function”)
my_function()
Introduction To Python Programming 48
Bibliography
1. Python: The Complete Reference Paperback – 20 March 2018 by Martin C.
Brown (Author)
2. Python Programming: Using Problem Solving Approach By Reema Thareja
(Author)
3. Python Crash Course: A Hands-On, Project-Based Introduction to Program-
ming by Eric Matthes
e-References
● https://www.amazon.in/Basic-Core-Python-Programming-Applica-
tions-ebook/dp/B0933F73LK
● https://slideplayer.com/slide/13549208/#.Y6AeQ1THs4I.gmail
● https://docs.python.org/3/whatsnew/3.11.html
49 Introduction To Python Programming
INTRODUCTION TO PYTHON PROGRAMMING
Module 2
Unit 2
Functions in Python
Introduction To Python Programming 50
Unit Table of Contents
Unit 2 Functions in Python
Aim _______________________________________________________ 52
Instructional Objectives _______________________________________ 52
Learning Outcomes___________________________________________ 52
2.2 Python Function Arguments __________________________________53
2.2.1 Python For Loops _____________________________________58
Self-Assessment Questions _____________________________________60
Answer Keys_________________________________________________63
Bibliography__________________________________________________64
e-References_________________________________________________64
51 Introduction To Python Programming
Aim
When student complete operators with Python, they will be able to: Build basic pro-
grams using all operators, conditional logic, looping, and functions.
Work with user input to create interactive programs.
Instructional Objectives
To learn more about python programming students can enrich their knowl-
edge in the following areas
● Able to do coding in Python Operators
● Able to do coding in conditional statements in Python
● Able to perform looping construction is python
Learning Outcomes
Upon completion of this unit, you will be able to:
● Describe the purpose of an operator
● List the different categories of operators
● Describe the concept of operator precedence
● Describing the concept of conditional statements and looping
Introduction To Python Programming 52
Python Function Arguments
As mentioned earlier, a function can also have arguments. A arguments is a value that is ac-
cepted by a function. For example,
# function with two arguments
def add_numbers(num1, num2):
sum = num1 + num2
print('Sum: ',sum)
# function with no argument
def add_numbers():
# code
If we create a function with arguments, we need to pass the corresponding values while calling
them.
For example,
# function call with two values
add_numbers(5, 4)
# function call with no value
add_numbers()
Here, add_numbers(5, 4) specifies that arguments num1 and num2 will get values 5 and 4
respectively.
Example 1: Python Function Arguments
# function with two arguments
def add_numbers(num1, num2):
sum = num1 + num2
print(“Sum: “,sum)
# function call with two values
add_numbers(5, 4)
# Output: Sum: 9
53 Introduction To Python Programming
In the above example, we have created a function named add_numbers() with arguments:
num1 and num2.
{Working of function with arguments}
We can also call the function by mentioning the argument name as:
add_numbers(num1 = 5, num2 = 4)
In Python, we call it Keyword Argument (or named argument). The code above is equivalent to
add_numbers(5, 4)
Example 2: Add Two Numbers
# function that adds two numbers
def add_numbers(num1, num2):
sum = num1 + num2
return sum
# calling function with two values
result = add_numbers(5, 4)
print('Sum: ', result)
Output
Sum: 9
Python Library Functions
In Python, standard library functions are the built-in functions that can be used directly in our
program.
For example,
● print() - prints the string inside the quotation marks
● sqrt() - returns the square root of a number
● pow() - returns the power of a number
These library functions are defined inside the module. And, to use them we must include the
module inside our program. For example, sqrt() is defined inside the math module.
Introduction To Python Programming 54
Example : Python Library Function
import math
# sqrt computes the square root
square_root = math.sqrt(4)
print("Square Root of 4 is",square_root)
# pow() comptes the power
power = pow(2, 3)
print("2 to the power 3 is",power)
Output
Square Root of 4 is 2.0
2 to the power 3 is 8
In the above example, we have used
● math.sqrt(4) - to compute the square root of 4
● pow(2, 3) - computes the power of a number i.e. 23
Here, notice the statement,
import math
Since sqrt() is defined inside the math module, we need to include it in our program.
Benefits of Using Functions
1. Code Reusable - We can use the same function multiple times in our program which makes
our code reusable. For example,
# function definition
def get_square(num):
return num * num
for i in [1,2,3]:
# function call
result = get_square(i)
print(‘Square of’,i, ‘=’,result)
55 Introduction To Python Programming
Output
Square of 1 = 1
Square of 2 = 4
Square of 3 = 9
In the above example, we have created the function named get_square() to calculate the
square of a number. Here, the function is used to calculate the square of numbers from 1 to 3.
Hence, the same method is used again and again.
2. Code Readability : Functions help us break our code into chunks to make our program read-
able and easy to understand.
Python Conditions and If statements
Python supports the usual logical conditions from mathematics:
● Equals: a == b
● Not Equals: a != b
● Less than: a < b
● Less than or equal to: a <= b
● Greater than: a > b
● Greater than or equal to: a >= b
These conditions can be used in several ways, most commonly in “if statements” and loops.
An “if statement” is written by using the if keyword.
ExampleIf statement:
a = 22
b = 300
if b > a:
print(“b is greater than a”)
The else keyword catches anything which isn’t caught by the preceding conditions.
Introduction To Python Programming 56
Example
x = 100
y = 23
if x > y:
print(“x is greater than y”)
else:
print(“y is greater than x”)
Elif
The elif keyword is pythons way of saying “if the previous conditions were not true, then try this
condition”.
Example
a = 44
b = 44
if b > a:
print(“b is greater than a”)
elif a == b:
print(“a and b are equal”)
And
The and keyword is a logical operator, and is used to combine conditional statements:
Example
Test if a is greater than b, AND if c is greater than a:
a = 100
b = 23
c = 500
if a > b and c > a:
print(“Both conditions are True”)
Or
The or keyword is a logical operator, and is used to combine conditional statements:
57 Introduction To Python Programming
Example
Test if a is greater than b, OR if a is greater than c:
a = 100
b = 23
c = 400
if a > b or a > c:
print("At least one of the conditions is True")
Nested If
You can have if statements inside if statements, this is called nested if statements.
Example
x = 51
if x > 10:
print(“Above ten,”)
if x > 20:
print(“and also above 20!”)
else:
print(“but not above 20.”)
2.2.1 Python For Loops
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or
a string).
This is less like the for keyword in other programming languages, and works more like an itera-
tor method as found in other object-orientated programming languages.
With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.
Example
Print each fruit in a fruit list:
fruits = [“apple”, “banana”, “orange”]
for x in fruits:
print(x)
Introduction To Python Programming 58
Looping Through a String
Even strings are iterable objects, they contain a sequence of characters:
Example
Loop through the letters in the word "banana":
for x in "banana":
print(x)
Output
b
a
n
a
n
a
59 Introduction To Python Programming
Self-Assessment Questions
1. What will be the datatype of the sample in the below code snippet?
sample=25
print(type(sample))
sample=”Welcome”
print(type(sample))
(a) str and int
(b) int and int
(c) str and str
(d) int and str
2. What will be the output of the following python code snippet?
print(2**4 + (4+4)**2)
(a) Error
(b) 80
(c) 100
(d) 117
3. Operators with the sample precedence are evaluated in which manner?
(a) Left to Right
(b) Right to Left
(c) Left to Left
(d) None
4. What is the meaning of >>> in Python Language?
(a) Compiler is Ready to take instruction
(b) Interpreter is ready take instruction
(c) Ready mode
(d) None
Introduction To Python Programming 60
Self-Assessment Questions
5. Which one of the following is a valid Python if statement.
(a) if a>=2 :
(b) if (a >= 2)
(c) if (a => 22)
(d) if a >= 22
6. What keyword would you use to add an alternative condition to an if statement?
(a) else if
(b) elseif
(c) elif
(d) None of the above
7. Find the output of the given Python program?
a = 45
if a < 15:
print(“Welcome”)
if a <= 80:
print(“Ready”)
else:
print(“Know your limit”)
(a) Right Welcome
(b) Ready
(c) Know your limit
(d) None of the above
61 Introduction To Python Programming
Self-Assessment Questions
8. What will be the output of the following Python code?
x = ‘abcd’
for i in x:
print(i)
x.upper()
(a) aBCD
(b) abcd
(c) ABCD
(d) error
9. What will be the output of the expression, 25 % 3 is?
(a) 7
(b) 1
(c) 0
(d) 5
10. What is the output of this expression, 3*1**3?
(a) 27
(b) 9
(c) 3
(d) 1
Introduction To Python Programming 62
Answer Keys
Self-Assessment Questions
Question No. Answers
1 d
2 b
3 a
4 b
5 a
6 c
7 b
8 b
9 b
10 d
63 Introduction To Python Programming
Bibliography
1. Python: The Complete Reference Paperback – 20 March 2018 by Martin C.
Brown (Author)
2. Python Programming: Using Problem Solving Approach By Reema Thareja
(Author)
3. Python Crash Course: A Hands-On, Project-Based Introduction to Program-
ming by Eric Matthes
e-References
● https://www.amazon.in/Basic-Core-Python-Programming-Applica-
tions-ebook/dp/B0933F73LK
● https://slideplayer.com/slide/13549208/#.Y6AeQ1THs4I.gmail
● https://docs.python.org/3/whatsnew/3.11.html
Introduction To Python Programming 64
INTRODUCTION TO PYTHON PROGRAMMING
Module 3
Introduction to Numpy
65 Introduction To Python Programming
Module3 Description
IThis module will help you get acquainted with the widely used array-processing library in Python,
NumPy. What is NumPy? NumPy is a general-purpose array-processing package. It provides a
high-performance multidimensional array object, and tools for working with these arrays. It is the
fundamental package for scientific computing with Python. It is open-source software. It contains
various features including these important ones:
● A powerful N-dimensional array object
● Sophisticated (broadcasting) functions
● Tools for integrating C/C++ and Fortran code
● Useful linear algebra, Fourier transform, and random number capabilities
Besides its obvious scientific uses, NumPy can also be used as an efficient multi-dimensional
container of generic data. Arbitrary data-types can be defined using NumPy which allows NumPy
to seamlessly and speedily integrate with a wide variety of databases.
Installation:
● Mac and Linux users can install NumPy via pip command:
pip install NumPy
● Windows does not have any package manager analogous to that in linux or mac. Please
download the pre-built windows installer for NumPy from here (according to your system
configuration and Python version). And then install the packages manually.
Introduction To Python Programming 66
INTRODUCTION TO PYTHON PROGRAMMING
Module 3
Introduction to Numpy
Unit 1
Numpy Array
67 Introduction To Python Programming
Table of Contents
Unit 1 Numpy Array
Aim ________________________________________________________69
Instructional Objectives_________________________________________69
Learning Outcomes____________________________________________69
3.1.1 NumPy Array ____________________________________________70
3.1.1NumPy - Ndarray Object _______________________________72
3.1.2 NumPy - Data Types__________________________________74
3.1.3 Data Type Objects (dtype)______________________________76
3.1.4 NumPy - Indexing & Slicing_____________________________81
Bibliography__________________________________________________83
e-References_________________________________________________83
Introduction To Python Programming 68
Aim
To introduce students to the basic concepts of programming
Familiarise students with Programming such as Python Programming,
functions, and the importance of programming in today’sworld
Instructional Objectives
To make you enthusiastic about learning of Python Programming
fundamentals
● Demonstrate why programming are important components in various indus-
tries
● Describe the widespread use of Programming in education, business, and
other fields like Data Science, Web Development, Artificial Intelligence.
● Explain to you the Installation of Python on our computer.
● Discuss the basic commands and programs use in the real world
Learning Outcomes
Upon completion of this unit, you will be able to:
● Define a computer programming and its importance
● Understand and use the basic python commands
● Able to install Python Programming
● Identify the basic components and applications of a python Programming
69 Introduction To Python Programming
3.1 Introduction to NumPy
NumPy is a Python package. It stands for 'Numerical Python'. It is a library consisting of multidi-
mensional array objects and a collection of routines for processing of array.
Numeric, the ancestor of NumPy, was developed by Jim Hugunin. Another package Numarray
was also developed, having some additional functionalities. In 2005, Travis Oliphant created
NumPy package by incorporating the features of Numarray into Numeric package. There are
many contributors to this open source project.
Operations using NumPy
Using NumPy, a developer can perform the following operations −
● Mathematical and logical operations on arrays.
● Fourier transforms and routines for shape manipulation.
● Operations related to linear algebra. NumPy has in-built functions for linear algebra and
random number generation.
NumPy – A Replacement for MatLab
NumPy is often used along with packages like SciPy (Scientific Python) and Mat−plotlib (plotting
library). This combination is widely used as a replacement for MatLab, a popular platform for
technical computing. However, Python alternative to MatLab is now seen as a more modern and
complete programming language.
It is open source, which is an added advantage of NumPy.
Standard Python distribution doesn't come bundled with NumPy module. A lightweight alterna-
tive is to install NumPy using popular Python package installer, pip.
pip install numpy
The best way to enable NumPy is to use an installable binary package specific to your oper-
ating system. These binaries contain full SciPy stack (inclusive of NumPy, SciPy, matplotlib,
IPython, SymPy and nose packages along with core Python).
Windows
Anaconda (from https://www.continuum.io) is a free Python distribution for SciPy stack. It is also
available for Linux and Mac.
Canopy (https://www.enthought.com/products/canopy/) is available as free as well as commer-
cial distribution with full SciPy stack for Windows, Linux and Mac.
Introduction To Python Programming 70
Python (x,y): It is a free Python distribution with SciPy stack and Spyder IDE for Windows OS.
(Downloadable from https://www.python-xy.github.io/)
Linux
Package managers of respective Linux distributions are used to install one or more packages in
SciPy stack.
Ubuntu
sudo apt-get install python-numpy
python-scipy python-matplotlibipythonipythonnotebook python-pandas
python-sympy python-nose
Fedora
sudo yum install numpyscipy python-matplotlibipython
python-pandas sympy python-nose atlas-devel
Building from Source
Core Python (2.6.x, 2.7.x and 3.2.x onwards) must be installed with distutils and zlib module
should be enabled.
GNU gcc (4.2 and above) C compiler must be available.
To install NumPy, run the following command.
Python setup.py install
To test whether NumPy module is properly installed, try to import it from Python prompt.
import numpy
If it is not installed, the following error message will be displayed.
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
import numpy
ImportError: No module named 'numpy'
Alternatively, NumPy package is imported using the following syntax −
import numpy as np
71 Introduction To Python Programming
3.1.1 NumPy - Ndarray Object
The most important object defined in NumPy is an N-dimensional array type called ndarray. It
describes the collection of items of the same type. Items in the collection can be accessed using
a zero-based index.
Every item in an ndarray takes the same size of block in the memory. Each element in ndarray is
an object of data-type object (called dtype).
Any item extracted from ndarray object (by slicing) is represented by a Python object of one of
array scalar types. The following diagram shows a relationship between ndarray, data type object
(dtype) and array scalar type −
Head
Data- type Array
scalar
Header
Ndarray
An instance of ndarray class can be constructed by different array creation routines described
later in the tutorial. The basic ndarray is created using an array function in NumPy as follows −
numpy.array
It creates an ndarray from any object exposing array interface, or from any method that returns
an array.
numpy.array(object, dtype = None, copy = True, order = None, subok = False, ndmin = 0)
The above constructor takes the following parameters −
Introduction To Python Programming 72
Sr.No. Parameter & Description
object
1 Any object exposing the array interface method returns an array, or any (nested)
sequence.
Dtype
2 Desired data type of array, optional
Copy
3 Optional. By default (true), the object is copied
Order
4 C (row major) or F (column major) or A (any) (default)
Subok
By default, returned array forced to be a base class array. If true, sub-classes passed
5
through
Ndmin
6 Specifies minimum dimensions of resultant array
Take a look at the following examples to understand better.
Example 1
import numpy as np
a = np.array([1,2,3])
print a
The output is as follows −
[1, 2, 3]
Example 2
# more than one dimensions
import numpy as np
a = np.array([[1, 2], [3, 4]])
print a
The output is as follows −
[[1, 2]
[3, 4]]
73 Introduction To Python Programming
Example 3
# minimum dimensions
import numpy as np
a = np.array([1, 2, 3,4,5], ndmin = 2)
print a
The output is as follows −
[[1, 2, 3, 4, 5]]
Example 4
# dtype parameter
import numpy as np
a = np.array([1, 2, 3], dtype = complex)
print a
The output is as follows −
[ 1.+0.j, 2.+0.j, 3.+0.j]
The ndarray object consists of contiguous one-dimensional segment of computer memory, com-
bined with an indexing scheme that maps each item to a location in the memory block.
3.1.2 NumPy - Data Types
NumPy supports a much greater variety of numerical types than Python does. The following
table shows different scalar data types defined in NumPy.
Sr.No. Data Types & Description
bool_
1
Boolean (True or False) stored as a byte
int_
2
Default integer type (same as C long; normally either int64 or int32)
intc
3
Identical to C int (normally int32 or int64)
intp
4
Integer used for indexing (same as C ssize_t; normally either int32 or int64)
int8
5
Byte (-128 to 127)
int16
6
Integer (-32768 to 32767)
int32
7
Integer (-2147483648 to 2147483647)
Introduction To Python Programming 74
Sr.No. Data Types & Description
int64
8
Integer (-9223372036854775808 to 9223372036854775807)
uint8
9
Unsigned integer (0 to 255)
uint16
10
Unsigned integer (0 to 65535)
uint32
11
Unsigned integer (0 to 4294967295)
uint64
12
Unsigned integer (0 to 18446744073709551615)
float_
13
Shorthand for float64
float16
14
Half precision float: sign bit, 5 bits exponent, 10 bits mantissa
float32
15
Single precision float: sign bit, 8 bits exponent, 23 bits mantissa
float64
16
Double precision float: sign bit, 11 bits exponent, 52 bits mantissa
complex_
17 Shorthand for complex128
complex64
18 Complex number, represented by two 32-bit floats (real and imaginary components)
complex128
19 Complex number, represented by two 64-bit floats (real and imaginary components)
NumPy numerical types are instances of dtype (data-type) objects, each having unique charac-
teristics. The dtypes are available as np.bool_, np.float32, etc.
75 Introduction To Python Programming
3.1.3 Data Type Objects (dtype)
A data type object describes interpretation of fixed block of memory corresponding to an array,
depending on the following aspects −
● Type of data (integer, float or Python object)
● Size of data
● Byte order (little-endian or big-endian)
● In case of structured type, the names of fields, data type of each field and part of the
memory block taken by each field.
● If data type is a subarray, its shape and data type
The byte order is decided by prefixing '<' or '>' to data type. '<' means that encoding is little-en-
dian (least significant is stored in smallest address). '>' means that encoding is big-endian
(most significant byte is stored in smallest address).
A dtype object is constructed using the following syntax −
numpy.dtype(object, align, copy)
The parameters are −
● Object − To be converted to data type object
● Align − If true, adds padding to the field to make it similar to C-struct
● Copy − Makes a new copy of dtype object. If false, the result is reference to builtin data
type object
Example
# using array-scalar type
import numpy as np
dt = np.dtype(np.int32)
print dt
output
int32
Introduction To Python Programming 76
Example
#int8, int16, int32, int64 can be replaced by equivalent string 'i1', 'i2','i4', etc.
import numpy as np
dt = np.dtype('i4')
print dt
Output
int32
Each built-in data type has a character code that uniquely identifies it.
● 'b' − boolean
● 'i' − (signed) integer
● 'u' − unsigned integer
● 'f' − floating-point
● 'c' − complex-floating point
● 'm' − timedelta
● 'M' − datetime
● 'O' − (Python) objects
● 'S', 'a' − (byte-)string
● 'U' − Unicode
● 'V' − raw data (void)
Ndarray.shape
This array attribute returns a tuple consisting of array dimensions. It can also be used to resize
the array.
Example
import numpy as np
a = np.array([[1,2,3],[4,5,6]])
print a.shape
Output
(2, 3)
77 Introduction To Python Programming
Example
# this resizes the ndarray
import numpy as np
a = np.array([[1,2,3],[4,5,6]])
a.shape = (3,2)
print a
Output
[[1, 2]
[3, 4]
[5, 6]]
Example
NumPy also provides a reshape function to resize an array.
import numpy as np
a = np.array([[1,2,3],[4,5,6]])
b = a.reshape(3,2)
print b
Output
[[1, 2]
[3, 4]
[5, 6]]
Ndarray.ndim
This array attribute returns the number of array dimensions.
Example
# an array of evenly spaced numbers
import numpy as np
a = np.arange(24)
print a
Introduction To Python Programming 78
Output
[0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23]
Example
# this is one dimensional array
import numpy as np
a = np.arange(24)
a.ndim
# now reshape it
b = a.reshape(2,4,3)
print b
# b is having three dimensions
Output
[[[ 0, 1, 2]
[ 3, 4, 5]
[ 6, 7, 8]
[ 9, 10, 11]]
[[12, 13, 14]
[15, 16, 17]
[18, 19, 20]
[21, 22, 23]]]
Numpy.empty
It creates an uninitialized array of specified shape and dtype. It uses the following constructor −
numpy.empty(shape, dtype = float, order = 'C')
The constructor takes the following parameters.
Sr.No. Parameter & Description
Shape
1
Shape of an empty array in int or tuple of int
Dtype
2
Desired output data type. Optional
Order
3
‘C’ for C-style row-major array, ‘F’ for FORTRAN style column-major array
79 Introduction To Python Programming
Example
The following code shows an example of an empty array.
import numpy as np
x = np.empty([3,2], dtype = int)
print x
Output
[[22649312 1701344351]
[1818321759 1885959276]
[16779776 156368896]]
Note − The elements in an array show random values as they are not initialized.
numpy.zeros
Returns a new array of specified size, filled with zeros.
numpy.zeros(shape, dtype = float, order = ‘C’)
The constructor takes the following parameters.
Sr.No. Parameter & Description
Shape
1 Shape of an empty array in int or sequence of int
Dtype
2 Desired output data type. Optional
Order
3 ‘C’ for C-style row-major array, ‘F’ for FORTRAN style column-major array
Example
# array of five zeros. Default dtype is float
import numpy as np
x = np.zeros(5)
print x
Output
[ 0. 0. 0. 0. 0.]
Introduction To Python Programming 80
Example
import numpy as np
x = np.zeros((5,), dtype = np.int)
print x
Output
[0 0 0 0 0]
Example
# custom type
import numpy as np
x = np.zeros((2,2), dtype = [(‘x’, ‘i4’), (‘y’, ‘i4’)])
print x
Output
[[(0,0)(0,0)]
[(0,0)(0,0)]]
3.1.4 NumPy - Indexing & Slicing
Contents of ndarray object can be accessed and modified by indexing or slicing, just like Python’s
in-built container objects.
As mentioned earlier, items in ndarray object follows zero-based index. Three types of indexing
methods are available − field access, basic slicing and advanced indexing.
Basic slicing is an extension of Python’s basic concept of slicing to n dimensions. A Python slice
object is constructed by giving start, stop, and step parameters to the built-in slice function. This
slice object is passed to the array to extract a part of array.
Example
import numpy as np
a = np.arange(10)
s = slice(2,7,2)
print a[s]
81 Introduction To Python Programming
Output
[2 4 6]
In the above example, an ndarray object is prepared by arange() function. Then a slice object is
defined with start, stop, and step values 2, 7, and 2 respectively. When this slice object is passed
to the ndarray, a part of it starting with index 2 up to 7 with a step of 2 is sliced.
The same result can also be obtained by giving the slicing parameters separated by a colon :
(start:stop:step) directly to the ndarray object.
Example
import numpy as np
a = np.arange(10)
b = a[2:7:2]
print b
Output
[2 4 6]
Introduction To Python Programming 82
Bibliography
1. Python: The Complete Reference Paperback – 20 March 2018 by Martin C.
Brown (Author)
2. Python Programming: Using Problem Solving Approach By Reema Thareja
(Author)
3. Python Crash Course: A Hands-On, Project-Based Introduction to Program-
ming by Eric Matthes
e-References
● https://www.amazon.in/Basic-Core-Python-Programming-Applica-
tions-ebook/dp/B0933F73LK
● https://slideplayer.com/slide/13549208/#.Y6AeQ1THs4I.gmail
● https://docs.python.org/3/whatsnew/3.11.html
83 Introduction To Python Programming
INTRODUCTION TO PYTHON PROGRAMMING
Module 3
Introduction to Numpy
Unit 2
Pandas
Introduction To Python Programming 84
Table of Contents
Unit 1 Numpy Array
Aim ________________________________________________________86
Instructional Objectives_________________________________________86
Learning Outcomes____________________________________________86
3.2 Pandas Introduction ________________________________________87
3.2.1 What is a Series?______________________________________88
3.2.2 Labels_______________________________________________89
3.2.3 Pandas DataFrames ___________________________________90
3.2.4 Locate Row___________________________________________91
3.2.5 Series_______________________________________________91
3.2.6 DataFrame___________________________________________94
Self-Assessment Questions _____________________________________96
Answer Keys_________________________________________________98
Bibliography _________________________________________________99
e-References ________________________________________________99
85 Introduction To Python Programming
Aim
To introduce students to the basic concepts of programming
Familiarise students with Programming such as Python Programming,
functions, and the importance of programming in today’sworld
Instructional Objectives
To make you enthusiastic about learning of Python Programming
fundamentals
● Demonstrate why programming are important components in various indus-
tries
● Describe the widespread use of Programming in education, business, and
other fields like Data Science, Web Development, Artificial Intelligence.
● Explain to you the Installation of Python on our computer.
● Discuss the basic commands and programs use in the real world
Learning Outcomes
Upon completion of this unit, you will be able to:
● Define a computer programming and its importance
● Understand and use the basic python commands
● Able to install Python Programming
● Identify the basic components and applications of a python Programming
Introduction To Python Programming 86
3.2 Pandas Introduction
Pandas is a Python library used for working with data sets.
It has functions for analyzing, cleaning, exploring, and manipulating data.
The name "Pandas" has a reference to both "Panel Data", and "Python Data Analysis" and was
created by Wes McKinney in 2008.
Why Use Pandas?
Pandas allows us to analyze big data and make conclusions based on statistical theories.
Pandas can clean messy data sets, and make them readable and relevant.
Relevant data is very important in data science.
What Can Pandas Do?
Pandas gives you answers about the data. Like
● Is there a correlation between two or more columns?
● What is average value?
● Max value?
● Min value?
Pandas are also able to delete rows that are not relevant, or contains wrong values, like empty
or NULL values. This is called cleaning the data.
Where is the Pandas Codebase?
The source code for Pandas is located at this github repository https://github.com/pandas-dev/
pandas
Installation of Pandas
If you have Python and PIP already installed on a system, then installation of Pandas is very
easy.
Install it using this command:
C:\Users\Your Name>pip install pandas
If this command fails, then use a python distribution that already has Pandas installed like, Ana-
conda, Spyder etc.
87 Introduction To Python Programming
Import Pandas
Once Pandas is installed, import it in your applications by adding the import keyword:
import pandas
Now Pandas is imported and ready to use.
Example
import pandas
mydataset = {
‘cars’: [“BMW”, “Volvo”, “Ford”],
‘passings’: [3, 7, 2]
}
myvar = pandas.DataFrame(mydataset)
print(myvar)
What is a Series?
A Pandas Series is like a column in a table.
It is a one-dimensional array holding data of any type.
Example
Create a simple Pandas Series from a list:
import pandas as pd
a = [1, 7, 2]
myvar = pd.Series(a)
print(myvar)
Output
0 1
1 7
2 2
dtype: int64
Introduction To Python Programming 88
3.2.2 Labels
If nothing else is specified, the values are labeled with their index number. First value has index
0, second value has index 1 etc.
This label can be used to access a specified value.
Example
Return the first value of the Series:
print(myvar[0])
Output
1
Create Labels
With the index argument, you can name your own labels.
Example
Create your own labels:
import pandas as pd
a = [1, 7, 2]
myvar = pd.Series(a, index = [“x”, “y”, “z”])
print(myvar)
Output
x 1
y 7
z 2
dtype: int64
When you have created labels, you can access an item by referring to the label.
89 Introduction To Python Programming
Example
Return the value of "y":
print(myvar["y"])
Output
7
3.2.3 Pandas DataFrames
What is a DataFrame?
A Pandas DataFrame is a 2 dimensional data structure, like a 2 dimensional array, or a table
with rows and columns.
Example
Create a simple Pandas DataFrame:
import pandas as pd
data = {
“calories”: [420, 380, 390],
“duration”: [50, 40, 45]
}
#load data into a DataFrame object:
df = pd.DataFrame(data)
print(df)
Output
calories duration
0 420 50
1 380 40
2 390 45
Introduction To Python Programming 90
3.2.4 Locate Row
As you can see from the result above, the DataFrame is like a table with rows and columns.
Pandas use the loc attribute to return one or more specified row(s)
Example
Return row 0:
#refer to the row index:
print(df.loc[0])
Output
calories 420
duration 50
Name: 0, dtype: int64
Pandas
Python provides a library called pandas that is popular with data scientists and analysts. Pan-
das enable users to manipulate and analyze data using sophisticated data analysis tools.
Pandas provide two data structures that shape data into a readable form:
● Series
● DataFrame
3.2.5 Series
A pandas series is a one-dimensional data structure that comprises of key-value pair, where
keys/labels are the indices and values are the values stored on that index. It is similar to a python
dictionary, except it provides more freedom to manipulate and edit the data.
Series 1 Series 2
0 Item 1.1 0 Item 2.1
1 Item 1.2 1 Item 2.2
2 Item 1.3 2 Item 2.3
3 Item 1.4 3 Item 2.4
Representation of a series data structure
91 Introduction To Python Programming
Syntax
Initializing a series
We use pandas.Series()to initialize a series object using Pandas.
The syntax to initialize different series objects is shown below:
In the code example above, there are three different series initialized by providing a list to the
pandas.Series() method. Every element in the series has a label/index. By default, the indices
are similar to an array index e.g., start with 00 and end at N - 1N−1, where NN is the number of
elements in that list.
However, we can provide our indices by using the index parameter of the pandas.Series()
method.
Introduction To Python Programming 92
We can have indices with hashable data types e.g., integers and strings. Index values don't have
to be unique (shown in the above code example).
Moreover, you can name your series by passing a string to the name argument in the
pandas.Series() method:
93 Introduction To Python Programming
3.2.6 DataFrame
A pandas DataFrame is a two-dimensional data structure that can be thought of as a spread-
sheet. It can also be thought of as a collection of two or more series with common indices.
Series 1 Series 2
0 Item 1.1 0 Item 2.1
1 Item 1.2 1 Item 2.2
2 Item 1.3 2 Item 2.3
3 Item 1.4 3 Item 2.4
Series 1
0 Item 1.1 Item 2.1
1 Item 1.2 Item 2.2
2 Item 1.3 Item 2.3
3 Item 1.4 Item 2.4
Represenation of a pandas data frame
Syntax
Initializing a DataFrame
To initialize a DataFrame, use pandas.DataFrame():
Introduction To Python Programming 94
In the code example above, a DataFrame is initialized using a dictionary with two key-value pairs.
Every key in this dictionary represents a column in the resulting DataFrame and the value rep-
resents all the elements in this column.
Both of the lists comprising of fruits as values are used to make a Python dictionary which is then
passed to the pandas.DataFrame() method to make a DataFrame.
For the second DataFrame, we passed a list of indexes using the index argument in the pandas.
DataFrame() method to use our custom indices.
95 Introduction To Python Programming
Self-Assessment Questions
1. What does NumPy stand for?
(a) Numerical Python
(b) Natural Python
(c) Numeric Program
(d) Nonlinear Python
2. Which of the following is used to create an identity matrix in NumPy?
(a) zeros()
(b) ones()
(c) arange()
(d) eye()
3. What is the output of the following code?
import numpy as np
a = np.array([[1, 2], [3, 4]])
print(a)ndim)
(a) 0
(b) 1
(c) 2
(d) 3
4. Which of the following is used to find the maximum element in a NumPy array?
(a) max()
(b) maximum()
(c) amax()
(d) All of the above
5. Which of the following is used to find the sum of the elements in a NumPy array?
(a) cumsum()
(b) sum()
(c) All of the above
(d) None of the above
Introduction To Python Programming 96
Self-Assessment Questions
6. What is the output of the following code?
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
c = np.concatenate((a, b))
print(c)
(a) [[1, 2, 3], [4, 5, 6]]
(b) [[1, 4], [2, 5], [3, 6]]
(c) [1, 2, 3, 4, 5, 6]
(d) Error
7. PANDAS stans for______
(a) Panel Data
(b) Panel Data Analysis
(c) Panel Dash Board
(d) Pane Data Analyst
8. A pandas DataFrame is a _____data structure
(a) two-dimensional
(b) 1 dimensional
(c) Multi dimensional
(d) None of the above
9. A pandas series is a _____data structure that comprises of key-value pair
(a) One dimensional
(b) Two dimensional
(c) Multi dimensional
(d) None of the above
10. A Dataframe object is value mutable.
(a) True
(a) False
97 Introduction To Python Programming
Answer Keys
Self-Assessment Questions
Question No. Answers
1 A
2 D
3 C
4 D
5 B
6 C
7 A
8 A
9 A
10 A
Introduction To Python Programming 98
Bibliography
1. Python: The Complete Reference Paperback – 20 March 2018 by Martin C.
Brown (Author)
2. Python Programming: Using Problem Solving Approach By Reema Thareja
(Author)
3. Python Crash Course: A Hands-On, Project-Based Introduction to Program-
ming by Eric Matthes
e-References
● https://www.amazon.in/Basic-Core-Python-Programming-Applica-
tions-ebook/dp/B0933F73LK
● https://slideplayer.com/slide/13549208/#.Y6AeQ1THs4I.gmail
● https://docs.python.org/3/whatsnew/3.11.html
99 Introduction To Python Programming
INTRODUCTION TO PYTHON PROGRAMMING
Module 4
Introduction to Data visualization
Introduction To Python Programming 100
Module4 Description
Data visualization is the discipline of trying to understand data by placing it in a visual context
so that patterns, trends, and correlations that might not otherwise be detected can be exposed.
Python offers multiple great graphing libraries packed with lots of different features. Whether you
want to create interactive or highly customized plots, Python has an excellent library for you.
To get a little overview, here are a few popular plotting libraries:
● Matplotlib: low level, provides lots of freedom
● Pandas Visualization: easy to use interface, built on Matplotlib
● Seaborn: high-level interface, great default styles
● plotnine: based on R’s ggplot2, uses Grammar of Graphics
● Plotly: can create interactive plots
In this module, we will learn how to create basic plots using Matplotlib, Pandas visualization, and
Seaborn as well as how to use some specific features of each library. This module will focus on
the syntax and not on interpreting the graphs.
101 Introduction To Python Programming
INTRODUCTION TO PYTHON PROGRAMMING
Module 4
Introduction to Data visualization
Unit 1
Data Visualisation in Python using Matplotlib and
Seaborn
Introduction To Python Programming 102
Table of Contents
Unit 1 Data Visualisation in Python using Matplotlib and Seaborn
Aim ________________________________________________________104
Instructional Objectives_________________________________________104
Learning Outcomes____________________________________________104
4.1 Data Visualisation in Python using
Matplotlib and Seaborn ______________________________________105
4.1.1 Python Libraries _______________________________________105
4.1.2 Matplotlib ____________________________________________105
Bibliography _________________________________________________107
e-References _______________________ _________________________107
103 Introduction To Python Programming
Aim
To introduce students to the basic concepts of programming
Familiarise students with Programming such as Python Programming,
functions, and the importance of programming in today’sworld
Instructional Objectives
To make you enthusiastic about learning of Python Programming
fundamentals
● Demonstrate why programming are important components in various indus-
tries
● Describe the widespread use of Programming in education, business, and
other fields like Data Science, Web Development, Artificial Intelligence.
● Explain to you the Installation of Python on our computer.
● Discuss the basic commands and programs use in the real world
Learning Outcomes
Upon completion of this unit, you will be able to:
● Define a computer programming and its importance
● Understand and use the basic python commands
● Able to install Python Programming
● Identify the basic components and applications of a python Programming
Introduction To Python Programming 104
4.1 Data Visualisation in Python using Matplotlib and Seaborn
It may sometimes seem easier to go through a set of data points and build insights from it but
usually this process may not yield good results. There could be a lot of things left undiscovered
as a result of this process. Additionally, most of the data sets used in real life are too big to do any
analysis manually. This is essentially where data visualization steps in.
Data visualization is an easier way of presenting the data, however complex it is, to analyze
trends and relationships amongst variables with the help of pictorial representation.
The following are the advantages of Data Visualization
● Easier representation of compels data
● Highlights good and bad performing areas
● Explores relationship between data points
● Identifies data patterns even for larger data points
While building visualization, it is always a good practice to keep some below mentioned
points in mind
● Ensure appropriate usage of shapes, colors, and size while building visualization
● Plots/graphs using a co-ordinate system are more pronounced
● Knowledge of suitable plot with respect to the data types brings more clarity to the infor-
mation
● Usage of labels, titles, legends and pointers passes seamless information the wider au-
dience
4.1.1 Python Libraries
There are a lot of python libraries which could be used to build visualization like matplotlib, vispy,
bokeh, seaborn, pygal, folium, plotly, cufflinks, and networkx. Of the many, matplotlib and sea-
born seems to be very widely used for basic to intermediate level of visualizations.
4.1.2 Matplotlib
It is an amazing visualization library in Python for 2D plots of arrays, It is a multi-platform data
visualization library built on NumPy arrays and designed to work with the broader SciPy stack. It
was introduced by John Hunter in the year 2002. Let’s try to understand some of the benefits and
features of matplotlib
105 Introduction To Python Programming
● It’s fast, efficient as it is based on numpy and also easier to build
● Has undergone a lot of improvements from the open source community since inception
and hence a better library having advanced features as well
● Well maintained visualization output with high quality graphics draws a lot of users to it
● Basic as well as advanced charts could be very easily built
● From the users/developers point of view, since it has a large community support, resolv-
ing issues and debugging becomes much easier
● Matplotlib is a plotting library for creating static, animated, and interactive visualizations
in Python. Matplotlib can be used in Python scripts, the Python and IPython shell, web ap-
plication servers, and various graphical user interface toolkits like Tkinter, awxPython, etc.
● Note: For more information, refer to Python Matplotlib – An Overview
● nstallation
● To use Pyplot we must first download matplotlib module. The best way to do this is –
● pip install matplotlib
Introduction To Python Programming 106
Bibliography
1. Python: The Complete Reference Paperback – 20 March 2018 by Martin C.
Brown (Author)
2. Python Programming: Using Problem Solving Approach By Reema Thareja
(Author)
3. Python Crash Course: A Hands-On, Project-Based Introduction to Program-
ming by Eric Matthes
e-References
● https://www.amazon.in/Basic-Core-Python-Programming-Applica-
tions-ebook/dp/B0933F73LK
● https://slideplayer.com/slide/13549208/#.Y6AeQ1THs4I.gmail
● https://docs.python.org/3/whatsnew/3.11.html
107 Introduction To Python Programming
INTRODUCTION TO PYTHON PROGRAMMING
Module 4
Introduction to Data visualization
Unit 2
Usage of Pyplot, Pyplot Functions
Introduction To Python Programming 108
Unit Table of Contents
Unit 2 Usage of Pyplot, Pyplot Functions
Aim _______________________________________________________ 110
Instructional Objectives _______________________________________ 110
Learning Outcomes___________________________________________ 110
4.2 Pyplot___________________________________________________ 111
4.2.1 Seaborn _____________________________________________113
4.2.2 Box plot _____________________________________________113
4.2.3 Parameters___________________________________________114
4.2.4 Python3 _____________________________________________115
4.2.5 Histogram____________________________________________118
4.2.6 Matplotlib __________________________________________122
4.2.7 Line Chart____________________________________________123
4.2.8 Histogram____________________________________________124
4.2.9 Bar Chart ____________________________________________125
4.2.10 Pandas Visualization __________________________________126
4.2.11 Line Chart___________________________________________127
4.2.12 Heatmap____________________________________________134
4.2.13 Faceting____________________________________________136
4.2.14 Pairplot_____________________________________________137
4.2.15 Scatter matrix________________________________________138
Self-Assessment Questions _____________________________________139
Answer Keys_________________________________________________141
Bibliography _________________________________________________142
e-References_________________________________________________142
109 Introduction To Python Programming
Aim
To introduce students to the basic concepts of programming
Familiarise students with Programming such as Python Programming,
functions, and the importance of programming in today’sworld
Instructional Objectives
To make you enthusiastic about learning of Python Programming
fundamentals
● Demonstrate why programming are important components in various indus-
tries
● Describe the widespread use of Programming in education, business, and
other fields like Data Science, Web Development, Artificial Intelligence.
● Explain to you the Installation of Python on our computer.
● Discuss the basic commands and programs use in the real world
Learning Outcomes
Upon completion of this unit, you will be able to:
● Define a computer programming and its importance
● Understand and use the basic python commands
● Able to install Python Programming
● Identify the basic components and applications of a python Programming
Introduction To Python Programming 110
4.2 Pyplot
Pyplot is a Matplotlib module which provides a MATLAB-like interface. Matplotlib is designed to
be as usable as MATLAB, with the ability to use Python and the advantage of being free and
open-source. Each pyplot function makes some change to a figure: e.g., creates a figure, creates
a plotting area in a figure, plots some lines in a plotting area, decorates the plot with labels, etc.
The various plots we can utilize using Pyplot are Line Plot, Histogram, Scatter, 3D Plot, Image,
Contour, and Polar.
Syntax :
matplotlib.pyplot.plot(*args, scalex=True, scaley=True, data=None, **kwargs)
# Python program to show plot function
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
plt.axis([0, 6, 0, 20])
plt.show()
Output
111 Introduction To Python Programming
The plot function marks the x-coordinates(1, 2, 3, 4) and y-coordinates(1, 4, 9, 16) in a linear
graph with specified scales. [/caption]
Parameters: This function accepts parameters that enables us to set axes scales and format
the graphs. These parameters are mentioned below :-
● plot(x, y): plot x and y using default line style and color.
● plot.axis([xmin, xmax, ymin, ymax]): scales the x-axis and y-axis from minimum to maxi-
mum values
● plot.(x, y, color=’green’, marker=’o’, linestyle=’dashed’, linewidth=2, markersize=12): x
and y co-ordinates are marked using circular markers of size 12 and green color line
with — style of width 2
● plot.xlabel(‘X-axis’): names x-axis
● plot.ylabel(‘Y-axis’): names y-axis
● plot(x, y, label = ‘Sample line ‘) plotted Sample Line will be displayed as a legend
● For sake of example we will use Electricity Power Consumption datasets of India and
Bangladesh. Here, we are using Google Public Data as a data source.
Introduction To Python Programming 112
4.2.1 Seaborn
Conceptualized and built originally at the Stanford University, this library sits on top of matplot-
lib. In a sense, it has some flavors of matplotlib while from the visualization point, it is much
better than matplotlib and has added features as well. Below are its advantages
● Built-in themes aid better visualization
● Statistical functions aiding better data insights
● Better aesthetics and built-in plots
● Helpful documentation with effective examples
Nature of Visualization
Depending on the number of variables used for plotting the visualization and the type of vari-
ables, there could be different types of charts which we could use to understand the relation-
ship. Based on the count of variables, we could have
● Univariate plot(involves only one variable)
● Bivariate plot(more than one variable in required)
A Univariate plot could be for a continuous variable to understand the spread and distribution of
the variable while for a discrete variable it could tell us the count Similarly, a Bivariate plot for con-
tinuous variable could display essential statistic like correlation, for a continuous versus discrete
variable could lead us to very important conclusions like understanding data distribution across
different levels of a categorical variable. A bivariate plot between two discrete variables could also
be developed.
4.2.2 Box plot
A boxplot, also known as a box and whisker plot, the box and the whisker are clearly displayed
in the below image. It is a very good visual representation when it comes to measuring the data
distribution. Clearly plots the median values, outliers and the quartiles. Understanding data dis-
tribution is another important factor which leads to better model building. If data has outliers, box
plot is a recommended way to identify them and take necessary actions.
Syntax: seaborn.boxplot(x=None, y=None, hue=None, data=None, order=None, hue_or-
der=None, orient=None, color=None, palette=None, saturation=0.75, width=0.8, dodge=True,
fliersize=5, linewidth=None, whis=1.5, ax=None, **kwargs)
113 Introduction To Python Programming
4.2.3 Parameters:
x, y, hue: Inputs for plotting long-form data.
data: Dataset for plotting. If x and y are absent, this is interpreted as wide-form.
color: Color for all of the elements.
Returns: It returns the Axes object with the plot drawn onto it.
The box and whiskers chart shows how data is spread out. Five pieces of information are gen-
erally included in the chart
1. The minimum is shown at the far left of the chart, at the end of the left ‘whisker’
2. First quartile, Q1, is the far left of the box (left whisker)
3. The median is shown as a line in the center of the box
4. Third quartile, Q3, shown at the far right of the box (right whisker)
5. The maximum is at the far right of the box
As could be seen in the below representations and charts, a box plot could be plotted for one or
more than one variable providing very good insights to our data.
Representation of box plot.
Box plot representing multi-variate categorical variables
Introduction To Python Programming 114
4.2.4 Python3
# import required modules
import matplotlib as plt
import seaborn as sns
# Box plot and violin plot for Outcome vs BloodPressure
_, axes = plt.subplots(1, 2, sharey=True, figsize=(10, 4))
# box plot illustration
sns.boxplot(x=’Outcome’, y=’BloodPressure’, data=diabetes, ax=axes[0])
# violin plot illustration
sns.violinplot(x=’Outcome’, y=’BloodPressure’, data=diabetes, ax=axes[1])
Output for Box Plot and Violin Plot
115 Introduction To Python Programming
Python3
# Box plot for all the numerical variables
sns.set(rc={'figure.figsize': (16, 5)})
# multiple box plot illustration
sns.boxplot(data=diabetes.select_dtypes(include='number'))
Output Multiple Box PLot
Scatter Plot
Scatter plots or scatter graphs is a bivariate plot having greater resemblance to line graphs in the
way they are built. A line graph uses a line on an X-Y axis to plot a continuous function, while a
scatter plot relies on dots to represent individual pieces of data. These plots are very useful to see
if two variables are correlated. Scatter plot could be 2 dimensional or 3 dimensional.
Syntax: seaborn.scatterplot(x=None, y=None, hue=None, style=None, size=None, data=None,
palette=None, hue_order=None, hue_norm=None, sizes=None, size_order=None, size_norm=-
None, markers=True, style_order=None, x_bins=None, y_bins=None, units=None, estimator=-
None, ci=95, n_boot=1000, alpha=’auto’, x_jitter=None, y_jitter=None, legend=’brief’, ax=None,
**kwargs)
Parameters:
x, y: Input data variables that should be numeric.
data: Dataframe where each column is a variable and each row is an observation.
size: Grouping variable that will produce points with different sizes.
style: Grouping variable that will produce points with different markers.
palette: Grouping variable that will produce points with different markers.
markers: Object determining how to draw the markers for different levels.
alpha: Proportional opacity of the points.
Introduction To Python Programming 116
Returns: This method returns the Axes object with the plot drawn onto it.
Advantages of a scatter plot
● Displays correlation between variables
● Suitable for large data sets
● Easier to find data clusters
● Better representation of each data point
Python3
# import module
import matplotlib.pyplot as plt
# scatter plot illustration
plt.scatter(diabetes[‘DiabetesPedigreeFunction’], diabetes[‘BMI’])
Output 2D Scattered Plot
Python3
# import required modules
from mpl_toolkits.mplot3d import Axes3D
# assign axis values
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y = [5, 6, 2, 3, 13, 4, 1, 2, 4, 8]
z = [2, 3, 3, 3, 5, 7, 9, 11, 9, 10]
# adjust size of plot
sns.set(rc={'figure.figsize': (8, 5)})
117 Introduction To Python Programming
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(x, y, z, c='r', marker='o')
# assign labels
ax.set_xlabel('X Label'), ax.set_ylabel('Y Label'), ax.set_zlabel('Z Label')
# display illustration
plt.show()
Output 3D Scattered Plot
4.2.5 Histogram
Histograms display counts of data and are hence similar to a bar chart. A histogram plot can also
tell us how close a data distribution is to a normal curve. While working out statistical method, it is
very important that we have a data which is normally or close to a normal distribution. However,
histograms are univariate in nature and bar charts bivariate.
A bar graph charts actual counts against categories e.g. height of the bar indicates the number
of items in that category whereas a histogram displays the same categorical variables in bins.
Introduction To Python Programming 118
Bins are integral part while building a histogram they control the data points which are within a
range. As a widely accepted choice we usually limit bin to a size of 5-20, however this is totally
governed by the data points which is present.
Data visualization is the discipline of trying to understand data by placing it in a visual context
so that patterns, trends, and correlations that might not otherwise be detected can be exposed.
Python offers multiple great graphing libraries packed with lots of different features. Whether you
want to create interactive or highly customized plots, Python has an excellent library for you.
To get a little overview, here are a few popular plotting libraries:
● Matplotlib: low level, provides lots of freedom
● Pandas Visualization: easy to use interface, built on Matplotlib
● Seaborn: high-level interface, great default styles
● plotnine: based on R’s ggplot2, uses Grammar of Graphics
● Plotly: can create interactive plots
In this article, we will learn how to create basic plots using Matplotlib, Pandas visualization, and
Seaborn as well as how to use some specific features of each library. This article will focus on the
syntax and not on interpreting the graphs, which I will cover in another blog post.
In further articles, I will go over interactive plotting tools like Plotly, which is built on D3 and can
also be used with JavaScript.
Importing Datasets
In this article, we will use two freely available datasets. The Iris and Wine Reviews dataset, which
we can both load into memory using pandas read_csv method.
import pandas as pd
iris = pd.read_csv(‘iris.csv’, names=[‘sepal_length’, ‘sepal_width’, ‘petal_length’, ‘petal_width’,
‘class’])
print(iris.head())
Python
Copy
119 Introduction To Python Programming
sepal_length sepal_width petal_length petal_width class
0 5.1 3.5 1.4 0.2 leis-setosa
1 4.9 3.0 1.4 0.2 leis-setosa
2 4.7 3.2 1.3 0.2 leis-setosa
3 4.6 3.1 1.5 0.2 leis-setosa
4 5.0 3.6 1.4 0.2 leis-setosa
Iris dataset head
wine_reviews = pd.read_csv('winemag-data-130k-v2.csv', index_col=0)
wine_reviews.head()
Introduction To Python Programming 120
Descrip- Disigna- Prov- Re- Re- Taster_ Taster_twit-
Country points Price title variety Winery
tion bon ince gion_1 gion_2 name ter_handle
121
Aromas in- Nicosia
clude trop- Sicly & 2013
valuka bal- Kerin @keri- White
0 Italy ical fruit, 87 Nan saridin- Etha Nan vulka Nicosia
ance okeefe nokeefe blend
broom, ia bin-
brimston co(etha)
Quinta
This is ripe Quinta
dos avida- Portu-
Port- and fruity, Reger dos
1 Avodagos 87 15.0 Douro Nan Nan @vossroger gos 2011 guess
hgal wine that is voss advida-
avidagos red
smooth gos
red(duro)
Rainstrom
Tart and
2013
snappy, the Willa- Willa-
Paul greg- point
2 us flavors of Nan 87 14.0 Oregon mette mette @paulgwine Point gris Rainstrom
ult gris(will-
time flesh valley valley
mate
and
valley)
Pinapple St. julian
rid, lemon Lake 2013 re-
Reserve Mich- Alexander
3 us path and 87 13.0 michgan Nan Nan serve late riesling St. julian
lathe havest gan perthee
orange shore harvest
blosam riesling
sweet
Much like
cheeks
the regular Vinther’s re- Will- Will-
Paul gre- 2012 Sweet
4 us boothing serve whild 87 65.0 Oregon mette mette @paulgwine Point noir
gutt vinter’s cheeks
from 2012, child block valley valley
reserve
this
Introduction To Python Programming
wild child
Figure : Wine Review dataset head
4.2.6 Matplotlib
Matplotlib is the most popular Python plotting library. It is a low-level library with a Matlab-like
interface that offers lots of freedom at the cost of having to write more code.
To install Matplotlib, pip, and conda can be used.
pip install matplotlib
or
conda install matplotlib
Bash
Copy
Matplotlib is specifically suitable for creating basic graphs like line charts, bar charts, histograms,
etc. It can be imported by typing:
import matplotlib.pyplot as plt
Python
Copy
Scatter Plot
To create a scatter plot in Matplotlib, we can use the scatter method. We will also create a figure
and an axis using plt.subplots to give our plot a title and labels.
# create a figure and axis
fig, ax = plt.subplots()
# scatter the sepal_length against the sepal_width
ax.scatter(iris[‘sepal_length’], iris[‘sepal_width’])
# set a title and labels
ax.set_title(‘Iris Dataset’)
ax.set_xlabel(‘sepal_length’)
ax.set_ylabel(‘sepal_width’)
Python
Copy
Figure : Matplotlib Scatter plot
Introduction To Python Programming 122
We can give the graph more meaning by coloring each data point by its class. This can be done
by creating a dictionary that maps from class to color and then scattering each point on its own
using a for-loop and passing the respective color.
# create color dictionary
colors = {‘Iris-setosa’:’r’, ‘Iris-versicolor’:’g’, ‘Iris-virginica’:’b’}
# create a figure and axis
fig, ax = plt.subplots()
# plot each data-point
for i in range(len(iris[‘sepal_length’])):
ax.scatter(iris[‘sepal_length’][i], iris[‘sepal_width’][i],color=colors[iris[‘class’][i]])
# set a title and labels
ax.set_title(‘Iris Dataset’)
ax.set_xlabel(‘sepal_length’)
ax.set_ylabel(‘sepal_width’)
Python
Copy
Figure : Scatter Plot colored by class
4.2.7 Line Chart
In Matplotlib, we can create a line chart by calling the plot method. We can also plot multiple
columns in one graph by looping through the columns we want and plotting each column on the
same axis.
123 Introduction To Python Programming
# get columns to plot
columns = iris.columns.drop(['class'])
# create x data
x_data = range(0, iris.shape[0])
# create figure and axis
fig, ax = plt.subplots()
# plot each column
for column in columns:
ax.plot(x_data, iris[column])
# set title and legend
ax.set_title('Iris Dataset')
ax.legend()
Python
Copy
Figure : Line Chart
4.2.8 Histogram
In Matplotlib, we can create a Histogram using the hist method. If we pass categorical data like
the points column from the wine-review dataset, it will automatically calculate how often each
class occurs.
# create figure and axis
fig, ax = plt.subplots()
# plot histogram
ax.hist(wine_reviews['points'])
# set title and labels
ax.set_title('Wine Review Scores')
ax.set_xlabel('Points')
ax.set_ylabel('Frequency')
Python
Copy
Introduction To Python Programming 124
Figure : Histogram
4.2.9 Bar Chart
A bar chart can be created using the bar method. The bar chart isn’t automatically calculating the
frequency of a category, so we will use pandas value_counts method to do this. The bar chart is
useful for categorical data that doesn’t have a lot of different categories (less than 30) because
else it can get quite messy.
# create a figure and axis
fig, ax = plt.subplots()
# count the occurrence of each class
data = wine_reviews['points'].value_counts()
# get x and y data
points = data.index
frequency = data.values
# create bar chart
ax.bar(points, frequency)
# set title and labels
ax.set_title('Wine Review Scores')
ax.set_xlabel('Points')
ax.set_ylabel('Frequency')
Python
Copy
125 Introduction To Python Programming
Figure 7: Bar-Chart
4.2.10 Pandas Visualization
Pandas is an open-source, high-performance, and easy-to-use library providing data structures,
such as data frames and data analysis tools like the visualization tools we will use in this article.
Pandas Visualization makes it easy to create plots out of a pandas dataframe and series. It also
has a higher-level API than Matplotlib, and therefore we need less code for the same results.
Pandas can be installed using either pip or conda.
pip install pandas
or
conda install pandas
Bash
Copy
Scatter Plot
To create a scatter plot in Pandas, we can call <dataset>.plot.scatter() and pass it two arguments,
the name of the x-column and the name of the y-column. Optionally we can also give it a title.
iris.plot.scatter(x=’sepal_length’, y=’sepal_width’, title=’Iris Dataset’)
Python
Copy
Figure: Scatter Plot
Introduction To Python Programming 126
As you can see in the image, it is automatically setting the x and y label to the column names.
4.2.11 Line Chart
To create a line chart in Pandas we can call <dataframe>.plot.line(). While in Matplotlib, we need-
ed to loop through each column we wanted to plot, in Pandas we don’t need to do this because it
automatically plots all available numeric columns (at least if we don’t specify a specific column/s).
iris.drop(['class'], axis=1).plot.line(title='Iris Dataset')
Python
Copy
Figure 9: Line Chart
If we have more than one feature, Pandas automatically creates a legend for us, as seen in the
image above.
Histogram
In Pandas, we can create a Histogram with the plot.hist method. There aren’t any required argu-
ments, but we can optionally pass some like the bin size.
wine_reviews['points'].plot.hist()
Python
Copy
Figure : Histogram
127 Introduction To Python Programming
It’s also straightforward to create multiple histograms.
iris.plot.hist(subplots=True, layout=(2,2), figsize=(10, 10), bins=20)
Python
Copy
Figure : Multiple Histograms
The subplots argument specifies that we want a separate plot for each feature, and the layout
specifies the number of plots per row and column.
Bar Chart
To plot a bar chart, we can use the plot.bar() method, but before calling this, we need to get our
data. We will first count the occurrences using the value_count() method and then sort the occur-
rences from smallest to largest using the sort_index() method.
wine_reviews[‘points’].value_counts().sort_index().plot.bar()
Python
Copy
Introduction To Python Programming 128
Figure : Vertical Bar-Chart
It’s also really simple to make a horizontal bar chart using the plot.barh() method.
wine_reviews['points'].value_counts().sort_index().plot.barh()
Python
Copy
Figure : Horizontal Bar-Chart
We can also plot other data than the number of occurrences.
wine_reviews.groupby("country").price.mean().sort_values(ascending=False)[:5].plot.bar()
Python
Copy
129 Introduction To Python Programming
Figure : Countries with the most expensive wine(on average)
In the example above, we grouped the data by country, took the mean of the wine prices, ordered
it, and plotted the five countries with the highest average wine price.
Seaborn
Seaborn is a Python data visualization library based on Matplotlib. It provides a high-level inter-
face for creating attractive graphs.
Seaborn has a lot to offer. For example, you can create graphs in one line that would take multiple
tens of lines in Matplotlib. Its standard designs are awesome, and it also has a nice interface for
working with Pandas dataframes.
It can be imported by typing:
import seaborn as sns
Python
Copy
Scatter plot
We can use the .scatterplot method for creating a scatterplot, and just as in Pandas, we need to
pass it the column names of the x and y data, but now we also need to pass the data as an addi-
tional argument because we aren’t calling the function on the data directly as we did in Pandas.
sns.scatterplot(x='sepal_length', y='sepal_width', data=iris)
Python
Copy
Introduction To Python Programming 130
Figure : Scatterplot
We can also highlight the points by class using the hue argument, which is a lot easier than in
Matplotlib.
sns.scatterplot(x='sepal_length', y='sepal_width', hue='class', data=iris)
Python
Copy
Figure : Scatterplot colored by class
Line chart
To create a line chart, the sns.lineplot method can be used. The only required argument is the
data, which in our case are the four numeric columns from the Iris dataset. We could also use the
sns.kdeplot method, which smoothes the edges of the curves and therefore is cleaner if you have
a lot of outliers in your dataset.
sns.lineplot(data=iris.drop([‘class’], axis=1))
Python
Copy
131 Introduction To Python Programming
Figure : Line Chart
Histogram
To create a histogram in Seaborn, we use the sns.distplot method. We need to pass it the column
we want to plot, and it will calculate the occurrences itself. We can also pass it the number of bins
and if we want to plot a gaussian kernel density estimate inside the graph.
sns.distplot(wine_reviews['points'], bins=10, kde=False)
Python
Copy
Figure : Histogram
sns.distplot(wine_reviews['points'], bins=10, kde=True)
Figure : Histogram with Gaussian kernel density estimate
Introduction To Python Programming 132
Bar chart
In Seaborn, a bar chart can be created using the sns.countplot method and passing it the data.
sns.countplot(wine_reviews['points'])
Python
Copy
Figure : Bar-Chart
Other graphs
Now that you have a basic understanding of the Matplotlib, Pandas Visualization, and Seaborn
syntax, I want to show you a few other graph types that are useful for extracting insides.
For most of them, Seaborn is the go-to library because of its high-level interface that allows for
the creation of beautiful graphs in just a few lines of code.
Box plots
A Box Plot is a graphical method of displaying the five-number summary. We can create box plots
using seaborn's sns.boxplot method and passing it the data as well as the x and y column names.
df = wine_reviews[(wine_reviews['points']>=95) & (wine_reviews['price']<1000)]
sns.boxplot('points', 'price', data=df)
Python
Copy
Figure: Boxplot
133 Introduction To Python Programming
Box Plots, just like bar charts, are great for data with only a few categories but can get messy
quickly.
4.2.12 Heatmap
A Heatmap is a graphical representation of data where the individual values contained in a ma-
trix are represented as colors. Heatmaps are perfect for exploring the correlation of features in a
dataset. To get the correlation of the features inside a dataset, we can call <dataset>.corr(), which
is a Pandas dataframe method. This will give us the correlation matrix.
We can now use either Matplotlib or Seaborn to create the heatmap.
Matplotlib:
# get correlation matrix
corr = iris.corr()
fig, ax = plt.subplots()
# create heatmap
im = ax.imshow(corr.values)
# set labels
ax.set_xticks(np.arange(len(corr.columns)))
ax.set_yticks(np.arange(len(corr.columns)))
ax.set_xticklabels(corr.columns)
ax.set_yticklabels(corr.columns)
# Rotate the tick labels and set their alignment.
plt.setp(ax.get_xticklabels(), rotation=45, ha="right",
rotation_mode="anchor")
Python
Copy
Figure : Heatmap without annotations
Introduction To Python Programming 134
To add annotations to the heatmap, we need to add two for loops:
# get correlation matrix
corr = iris.corr()
fig, ax = plt.subplots()
# create heatmap
im = ax.imshow(corr.values)
# set labels
ax.set_xticks(np.arange(len(corr.columns)))
ax.set_yticks(np.arange(len(corr.columns)))
ax.set_xticklabels(corr.columns)
ax.set_yticklabels(corr.columns)
# Rotate the tick labels and set their alignment.
plt.setp(ax.get_xticklabels(), rotation=45, ha="right",
rotation_mode="anchor")
# Loop over data dimensions and create text annotations.
for i in range(len(corr.columns)):
for j in range(len(corr.columns)):
text = ax.text(j, i, np.around(corr.iloc[i, j], decimals=2),
ha="center", va="center", color="black")
Python
Copy
Figure: Heatmap with annotations
Seaborn makes it way easier to create a heatmap and add annotations:
sns.heatmap(iris.corr(), annot=True)
Python
Copy
135 Introduction To Python Programming
Figure : Heatmap with annotations
4.2.13 Faceting
Faceting is the act of breaking data variables up across multiple subplots and combining those
subplots into a single figure.
Faceting is helpful if you want to explore your dataset quickly.
To use one kind of faceting in Seaborn, we can use the FacetGrid. First of all, we need to define
the FacetGrid and pass it our data as well as a row or column, which will be used to split the data.
Then we need to call the map function on our FacetGrid object and define the plot type we want
to use and the column we want to graph.
g = sns.FacetGrid(iris, col='class')
g = g.map(sns.kdeplot, 'sepal_length')
Python
Copy
Figure 25: Facet-plot
Introduction To Python Programming 136
You can make plots bigger and more complicated than the example above. You can find a few
examples here.
4.2.14 Pairplot
Lastly, I will show you Seaborns pairplot and Pandas scatter_matrix, which enable you to plot a
grid of pairwise relationships in a dataset.
sns.pairplot(iris)
Python
Copy
Figure: Pairplot
from pandas.plotting import scatter_matrix
fig, ax = plt.subplots(figsize=(12,12))
scatter_matrix(iris, alpha=1, ax=ax)
Python
Copy
137 Introduction To Python Programming
4.2.15 Scatter matrix
As you can see in the images above, these techniques are always plotting two features with each
other. The diagonal of the graph is filled with histograms, and the other plots are scatter plots.
Introduction To Python Programming 138
Self-Assessment Questions
1. Which of the following does not visualize data?
(a) Charts
(b) Maps
(c) shapes
(d) Graphs
2. Which of the following type of chart is not supported by pyplot?
(a) Histogram
(b) Boxplot
(c) Pie
(d) All the above
3. Plot which is used to give statistical summary is _____
(a) Bar
(b) Line
(c) Histogram
(d) Box plot
4. Which of the following is not the parameter of pyplot’s plot() method?
(a) Marker
(a) Linehight
(a) Linestyle
(a) Color
5. To compare data we can use _____chart
(a) Line
(b) Bar
(c) Pie
(d) Scatter
139 Introduction To Python Programming
Self-Assessment Questions
6. Which of the following cart element is used to identify data series by its color pat-
terns?
(a) chair title
(b) Legend
(c) Marker
(d) Data labels
7. Recommanded way to load matplotlib library is
(a) import matplotlib.pyplot as plt
(b) import matplotlib.pyplot
(c) import matplotlib as plt
(d) import matplotlib
8.Which function can be used to export generated graph in matplotlib to png Bar
(a) savefigure
(b) savefig
(c) save
(d) export
9. Which method can be used to get the shortest path in networkx library
(a) shortest_path
(b) short_path
(c) shortestPath
(d) sortPath
10.which graph should be used If we want to find patterns in data?
(a) bar
(b) histogram
(c) scatterplots
(d) basemap
Introduction To Python Programming 140
Answer Keys
Self-Assessment Questions
Question No. Answers
1 C
2 D
3 D
4 B
5 B
6 B
7 A
8 B
9 A
10 C
141 Introduction To Python Programming
Bibliography
1. Python: The Complete Reference Paperback – 20 March 2018 by Martin C.
Brown (Author)
2. Python Programming: Using Problem Solving Approach By Reema Thareja
(Author)
3. Python Crash Course: A Hands-On, Project-Based Introduction to Program-
ming by Eric Matthes
e-References
● https://www.amazon.in/Basic-Core-Python-Programming-Applica-
tions-ebook/dp/B0933F73LK
● https://slideplayer.com/slide/13549208/#.Y6AeQ1THs4I.gmail
● https://docs.python.org/3/whatsnew/3.11.html
Introduction To Python Programming 142
143 Introduction To Python Programming