0% found this document useful (0 votes)
1 views68 pages

Ecap776 Programming in Python MCQ

Python is a high-level, general-purpose programming language created by Guido van Rossum in 1991, known for its cross-platform compatibility and use in web applications. Key features include the use of indentation for defining scope, various data types such as lists, tuples, and dictionaries, and control statements for managing loops. The document also includes self-assessment questions and further reading resources for learning Python.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views68 pages

Ecap776 Programming in Python MCQ

Python is a high-level, general-purpose programming language created by Guido van Rossum in 1991, known for its cross-platform compatibility and use in web applications. Key features include the use of indentation for defining scope, various data types such as lists, tuples, and dictionaries, and control statements for managing loops. The document also includes self-assessment questions and further reading resources for learning Python.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 68

Notes UNIT 1

Programming in Python

my_function("System")
Args is a common abbreviation for arguments in Python documentation.

Summary
 Python is a popular high-level, general-purpose programming language. Guido van Rossum
invented it in 1991, and the Python Software Foundation continued to advance it
 Web applications can be developed on a server using Python.
 Python is cross-platform compatible (Windows, Mac, Linux, Raspberry Pi, etc).
 Indentation, which utilises whitespace, is how Python defines scope, including the scope of
loops, functions, and classes. Curly-brackets are frequently used for this in other computer
languages.
 Operations on variables and values are carried out using operators.
 Loops are used in Python to continually iterate over a section of code. Control statements
are used to modify a loop's execution from its default behaviour.
 In Python, the break statement is used to end or remove the control from the loop that
contains the statement
 When a Python programme sees a continue statement, it skips the current iteration's
execution when the condition is satisfied and instead allows the loop to carry on to the next
iteration
 When the condition is met, the pass statement, a null operator, is used by the programmer to
do nothing.

Keywords
Python:The general-purpose, interactive, object-oriented, and high-level programming language
Python is particularly well-liked.
Python path: It has a role similar to PATH. This variable tells the Python interpreter where to
locate the module files imported into a program.
Python startup: It includes the location of a Python source code initialization file. Every time the
interpreter is launched, it is executed.
Unix:The original Python IDE for Unix is called IDLE.
Windows: The first Windows interface for Python is called PythonWin, and it is an IDE with a
GUI.
Macintosh:You can get the Macintosh version of Python and the IDLE IDE from the main website
in MacBinary or BinHex format.
Reserved Words:You cannot use them as identifier names for constants, variables, or anything
else.
Python Numbers: Number data types store numeric values.
Python Strings:Python defines strings as a contiguous group of characters that are enclosed in
quotation marks.
Python Lists:Of all the compound data types in Python, lists are the most flexible. Items in a list
are delimited by square brackets and separated by commas ([]).
Python Tuples: Another sequence data type that resembles the list is the tuple. A tuple is made up
of several values that are separated by commas.
Python Dictionaries: The dictionaries used by Python are something like hash tables. They
consist of key-value pairs and operate similarly to associative arrays or hashes seen in Perl.

12 LOVELY PROFESSIONAL UNIVERSITY


Notes

Unit 01: Python Basics

Self Assessment
Q1: Who was the Python programming language's creator?

A. Mark
B. Guido can Rossum
C. Alfred novel
D. Ralf Kleinberg

Q2: What programming languages does Python support?

A. Structural programming
B. Object-oriented programming
C. Functional programming
D. All of the above

Q3. Select the correct extension of python file

A. .ps
B. .pyth
C. .py
D. .thon

Q4: Select true statement

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

Q5: Which of the following is used in Python to define a block of code?

A. Key
B. Brackets
C. Indentation
D. All of the above

Q6: Which of the subsequent characters is used in Python to provide single-line comments?

A. //
B. #
C. /*
D. */

Q7: Which command is used to know the version of python

A. python -version
B. python -v
C. python -V
D. None of above

LOVELY PROFESSIONAL UNIVERSITY 13


Notes

Programming in Python

Q8: What is Python's precedence hierarchy?

A. Exponential, Parentheses, Multiplication, Division, Addition, Subtraction


B. Exponential, Parentheses, Division, Multiplication, Addition, Subtraction
C. Parentheses, Exponential, Multiplication, Division, Subtraction, Addition
D. Parentheses, Exponential, Multiplication, Division, Addition, Subtraction

Q9: PIP stands for

A. Program installer Preferrable


B. Preferred Installer Program
C. Parenthesis installer program
D. Program installer Parenthesis

Q10: In Python programming, which of the following is not a basic data type?

A. Dictionary
B. Class
C. Tuple
D. Lists

Q11: Which of the above statements in Python is used to generate an empty set?

A. Empty(a)
B. {}
C. set()
D. None of above

Q12: Which of the following describes how a function in Python is used?

A. For your application, functions don’t improve modularity.


B. you can't also write your own functions.
C. Functions are reusable programme components
D. Functions are reusable programme components.

Q13: Which of the following sentences is utilized in Python's Exception Handling?

A. try
B. except
C. finally
D. All of the above

14: Which of the following list items is a legitimate Python escape sequence?

A. \n
B. \t
C. \\
D. All of the above

14 LOVELY PROFESSIONAL UNIVERSITY


Notes

Unit 01: Python Basics

15. What language is written in Python?

A. C++
B. C
C. Java
D. None of these

Answers for Self Assessment


l. B 2. D 3. C 4. B 5. C

6. B 7. C 8. D 9. B 10. B

11. C 12. C 13. D 14. D 15. C

Review Questions
1. Write down steps to download and install python.
2. Write down challenges used in installing python.
3. Explain all python data types.
4. Explain control statements in python.
5. What is the difference between list and tuples in python.
6. What is Python? What is the benefit of using a python.

FurtherReadings
 Mark Lutz,Programming Python: Powerful Object-Oriented Programming, OREILLY
 Wes McKinney, Python for data analysis, OREILLY
 David Ascher and Mark Lutz, Learning Python, OREILLY
 Eric Matthes, Python Crash Course, 2nd Edition: A Hands-On, Project-Based
Introduction to Programming, Starch Pres

Web Links
https://www.tutorialspoint.com/python/index.htm
https://www.python.org/downloads/
https://www.w3schools.in/python/data-types
https://www.programiz.com/python-programming/online-compiler/
https://www.codecademy.com/catalog/language/python

LOVELY PROFESSIONAL UNIVERSITY 15


Notes
UNIT 2 Unit 02: Python Data Structures

dict.update(dict2)
9
Adds dictionary dict2's key-values pairs to dict

dict.values()
10
Returns list of dictionary dict's values

Summary
 Python's strings, like those of many other widely used programming languages, are
collections of bytes that represent unicode characters.
 Use the len() function to determine a string's length.
 The keyword in can be used to determine whether a specific word or character is present
in a string.
 The keyword not in can be used to determine whether a specific word or character DOES
NOT exist in a string.
 Use the + operator to concatenate, or merge, two strings.
 Similar to dynamically scaled arrays specified in other languages (such as vector in C++
and ArrayList in Java), Python lists are similar to them. A list is a group of items that are
denoted by the symbol [] and separated by commas.
 Refer to the index number to access the list entries. To retrieve a specific item in a list, type
[] in the index operator.
 In Python, positions from the array's end are represented by negative sequence indexes.
 Use of the built-in append() function allows for the addition of elements to the List. The
append() method can only add one element at a time to the list; loops must be used to add
many elements using the append() method.
 Python is a popular high-level, general-purpose programming language. Guido van
Rossum invented it in 1991, and the Python Software Foundation continued to advance it
 Web applications can be developed on a server using Python.

Keywords
Token:The smallest discrete unit in a Python programme is called a token. Tokens are used to
construct each statement and instruction in a programme.

Keywords:In a computer language, keywords are words that have a particular importance or
meaning. They cannot be utilised for any arbitrary reason, including as names for functions or
variables.
Identifiers:The names assigned to any variable, function, class, list, methods, etc. for identification
are known as identifiers.
Reserved Words:You cannot use them as identifier names for constants, variables, or anything
else.
Python Numbers: Number data types store numeric values.
Python Strings:Python defines strings as a contiguous group of characters that are enclosed in
quotation marks.
Literals or Values:The fixed values or data items used in a source code are known as literals.
Python Lists:Of all the compound data types in Python, lists are the most flexible. Items in a list
are delimited by square brackets and separated by commas ([]).

32 LOVELY PROFESSIONAL UNIVERSITY


Notes

Programming in Python

Python Tuples: Another sequence data type that resembles the list is the tuple. A tuple is made up
of several values that are separated by commas.
Python Dictionaries: The dictionaries used by Python are something like hash tables. They
consist of key-value pairs and operate similarly to associative arrays or hashes seen in Perl.
Dictionary: Key-value pairs are stored in dictionaries. To make the dictionary more efficient, Key-
Value is offered.

Review Questions
Q1. What will be the output of above Python code?
str1="8/2"
print("str1")
print(str1)

A. str1
B. str1 8/2
C. str1 4.0
D. str1

Q2. Which statement is not correct?

A. Strings cannot be changed.


B. The capitalization() function in the string type returns a string after changing the entire
input string to uppercase.
C. The lower() function in the string language is utilised to return a string by lowercasing the
entire input string.
D. None of these.

Q3. Select the correct output of the following program.


str1="Good Morning"
print(str1[2:8])

A. od Mor
B. od Morn
C. odMor
D. oodMor

Q4. What would be outout of following program.


str1="This Is my File"
str2=str1.replace('i','I')
print(str2)

A. This Is my File
B. ThIsis my File
C. ThIs Is my FIle
D. ThIs Is my File

LOVELY PROFESSIONAL UNIVERSITY 33


Notes

Unit 02: Python Data Structures

Q5. Select the correct output for the following code.


list1=['1','3','6','7']
str1="8"
for i in list1:
str1=str1+i
print(str1)

A. 81367
B. Error
C. 1367
D. 8 Error

Q6. What will following Python code return?


str1="This is my file"
print(len(str1))

A. 13
B. 14
C. 15
D. 16

Q7. What will following python code returns?


x = str(4)
y = int(4)
z = float(4)

print(x)
print(y)
print(z)

A. 4 4 4.0
B. 4.0 4 4
C. 4 4.0 4
D. None of above

Q8. What will following python code returns?


thistuple = tuple(("abc", "def", "ghi"))
print(len(thistuple))

A. 4
B. 5
C. 3
D. 9

Q9. What will following python code returns?

34 LOVELY PROFESSIONAL UNIVERSITY


Notes

Programming in Python

tuple3 = (True, False, False)


print(type(tuple3))

A. <class ‘list’>
B. <class ‘tuple’>
C. <class ‘boolean’>
D. None of above

Q10. What will following python code returns?


thisset = {"apple", "banana", "cherry", "apple"}
print(thisset)

A. {‘apple’,‘banana’,’cherry’,’apple’}
B. {‘banana’,’cherry’,’apple’,’apple’}
C. {‘banana’,’apple’}
D. {‘banana’,’cherry’,’apple’}

Q11. What will following python code returns?


thisdict = {
"Section": "D1601",
"Class": "BCA",
"year": 1964,
"year": 2020
}
print(thisdict)

A. {'Section': 'D1601', 'Class': 'BCA', 'year': 1964}


B. {'Section': 'D1601', 'Class': 'BCA', 'year': 2020, ’year’:1964}
C. {'Section': 'D1601', 'Class': 'BCA', 'year': 2020,1964}
D. {'Section': 'D1601', 'Class': 'BCA', 'year': 2020}

Q12. What will following python code returns?


thisdict = {
"Name": "Aalya",
"Section": "D1601",
"Class": "BCA"
}
x = thisdict.get("Section")
print(x)

A. D1601
B. Error
C. String not allowed
D. Type incompatible

LOVELY PROFESSIONAL UNIVERSITY 35


Notes

Unit 02: Python Data Structures

Q13What will following python code returns?


colors = ["red", "green", "burnt sienna", "blue"]
colors[2]

A. Green
B. Burnt sienna
C. Blue
D. Red

Q14: Which syntax use to delete dictonary.

A. del dict
B. Del dictionary
C. rmvdict
D. remove dictionary

Q15: Select right function of len()

A. compares element and then calculate length


B. gives total length of dictionary
C. Both a and b
D. None of above

Answers for Self Assessment


1. B 2. B 3. A 4. D 5. A

6. C 7. A 8. C 9. B 10. D

11. D 12. A 13. B 14. A 15. B

FurtherReadings
 Mark Lutz,Programming Python: Powerful Object-Oriented Programming, OREILLY
 Wes McKinney, Python for data analysis, OREILLY
 David Ascher and Mark Lutz, Learning Python, OREILLY
 Eric Matthes, Python Crash Course, 2nd Edition: A Hands-On, Project-Based
Introduction to Programming, Starch Pres

Web Links
https://www.tutorialspoint.com/python/index.htm
https://www.python.org/downloads/
https://www.w3schools.in/python/data-types
https://www.programiz.com/python-programming/online-compiler/
https://www.codecademy.com/catalog/language/python

36 LOVELY PROFESSIONAL UNIVERSITY


UNIT 3
Notes

Unit 03: OOP Concepts

Object-oriented Programming Procedural Programming

The approach to addressing problems that A list of instructions is used in procedural


uses objects for computation is called object- programming to perform calculations in
oriented programming. stages.

It makes development and upkeep simpler. When a project grows in scope, maintaining
the codes is difficult in procedural
programming.

It replicates the thing in the actual world. It doesn't represent reality in any way. It
Therefore, oops makes it simple to tackle operates using detailed instructions broken
difficulties in the actual world. down into smaller units called functions.

It offers data concealment. Consequently, it Because procedural languages don't offer a


is safer than procedural languages. Private suitable method for data binding, they are less
information is not accessible from anyplace. secure.

C++, Java, .Net, Python, C#, and other object- Procedural languages include C, Fortran,
oriented programming languages are Pascal, VB, and others.
examples.

Summary
 The Python programming style known as object-oriented programming (OOPs) makes use
of objects and classes.
 A class is a group of related items. The models or prototypes used to generate objects are
included in classes.
 The object is an entity that is connected to a state and activity. Any physical device, such as a
mouse, keyboard, chair, table, pen, etc., may be used.
 The constructors in Java and C++ are comparable to the __init__ method. As soon as a class
object is created, it is executed.
 A function connected to an object is the method. A method is not specific to class instances
in Python. Any sort of object may have methods.
 The capacity of one class to derive or inherit properties from another class is known as
inheritance.
 Simply put, polymorphism means having multiple forms. For instance, utilising
polymorphism, we can answer the question of whether the given species of birds fly or not
using just one function
 Both data abstraction and encapsulation are frequently used interchangeably. Since data
abstraction is accomplished by encapsulation, the two terms are almost synonymous
 One of the core ideas in object-oriented programming is encapsulation (OOP). It explains the
concept of data wrapping and the techniques that operate on data as a single unit.
 The approach to addressing problems that uses objects for computation is called object-
oriented programming.
 A list of instructions is used in procedural programming to perform calculations in stages

LOVELY PROFESSIONAL UNIVERSITY 45


Notes
Programming in Python

Keywords
OOPS: Object-oriented programming is known as OOP. While object-oriented programming
involves constructing objects that include both data and methods, procedural programming
involves developing procedures or methods that perform actions on the data.

Class: Python is an object oriented programming language. Almost everything in Python is an


object, with its properties and methods. A Class is like an object constructor, or a "blueprint" for
creating objects

The __init__method: All classes have a function called __init__(), which is always executed when
the class is being initiated.

The __str__function: What should be returned when the class object is rendered as a string is
determined by the __str__() function.

Objects methods: Methods can also be found in objects. Object-specific functions are called
methods in an object.

Self-Parameter: To access class-specific variables, use the self parameter, which is a reference to
the currently running instance of the class.

Del:Using the del keyword, properties on objects can be deleted.


Pass statement: Although class definitions cannot be empty, if for some reason you have one that
is empty, add the pass statement to prevent an error.

Inheritance: By using inheritance, we may create a class that has all the methods and
attributes of another class.
Parent class:The class being inherited from, often known as the base class, is the parent class.
Child class:The class that inherits from another class is referred to as a child class or derived class.
Super Function:The super() function in Python allows a descendant class to inherit all of its
parent's methods and properties.

Self Assessment
Q1. Which option best encapsulates inheritance?

A. Ability of a class to include methods from other classes in its definition


B. Techniques for grouping instance variables and methods to limit access to certain class
members
C. A focus on variables and passing variables to functions
D. Enables the use of sophisticated software that is well-designed and flexible.

Q2. Which of the following claims about inheritance is false?

A. A class's protected members may be inherited.


B. The class that inherits is known as a subclass.
C. A class's private members can be accessed and inherited.
D. One characteristic of OOP is inheritance
.
Q3. What line of code should you write to activate the __init__ method in A from B if B is a
subclass of A?

46 LOVELY PROFESSIONAL UNIVERSITY


Notes

Unit 03: OOP Concepts

A. A.__init__(self)
B. B.__init__(self)
C. A.__init__(B)
D. B.__init__(A)
Q4: What function type is a built-in in the context of classes?

A. Identifies the name of any value's object.


B. Identifies any value's class name.
C. Determines a value's class description
D. Identifies any value's file name

Q5: What one of the following is not an inheritance type?

A. Double-level
B. Multi-level
C. Single-level
D. Multiple

Q6: Which of these is not one of OOP's core characteristics?

A. Encapsulation
B. Inheritance
C. Instantiation
D. Polymorphism

Q7: Which of the following definitions best describes encapsulation?

A. The capacity of a class to derive individuals from other classes as part of its own definition.
B. Techniques for combining instance variables and methods to limit access to specific class
members
C. focuses on supplying parameters to functions and variables.
D. enables the use of sophisticated software that is well-designed and flexible.

Q8: Define Overriding.

A. Overriding can occur in the case of inheritance in class


B. It is a process of redefining inherited method in child class.
C. It is a magic method in python.
D. None of these

Q9: _____________ developed python language

A. Albert Einstein
B. Guido Van Rossum
C. Guido Evan
D. None of these

Q10: What year was the Python programming language created?

LOVELY PROFESSIONAL UNIVERSITY 47


Notes
Programming in Python

A. 1975
B. 1989
C. 1972
D. 1990
Q11: Which of the following commands the expression with the most precedence?

A. Addition
B. Subtraction
C. Parentheses
D. Power

Q12: Of the following, which best describes abstraction?

A. Hiding the execution


B. displaying crucial information
C. Hiding the important data
D. Hiding the implementation and showing only the features

Q13: A class is an ____________ abstraction.

A. Object
B. Logical
C. Real
D. Hypothetical

Q14: Abstraction can be used for _______________.

A. Control and data.


B. Only data
C. Only control
D. Classes

Q15: Which of the following can be considered a combination of data abstraction and
programming?

A. Class
B. Object
C. Inheritance
D. Interfaces

Answer for Self Assessment


l. A 2. C 3. A 4. B 5. A

6. C 7. B 8. B 9. B 10. B

11. C 12. D 13. B 14. A 15. B

48 LOVELY PROFESSIONAL UNIVERSITY


Notes

Unit 03: OOP Concepts

Review Questions
1. What do you understand by OOPS? Write down the code to make a python class that si
empty.
2. Define Objects. Write down example to create an object with methods.
3. What do you understand by inheritance and also define types of inheritance.
4. Write down difference between Single level inheritance, multilevel inheritance and multiple
inheritance.
5. Define Polymorphism. Write down python code that define use of polymorphism.
6. What do you understand by Encapsulation? Write down python program to demonstrate
private members.
7. Write down difference between object-oriented programming and procedural
programming.

FurtherReadings
 Mark Lutz,Programming Python: Powerful Object-Oriented Programming, OREILLY
 Wes McKinney, Python for data analysis, OREILLY
 David Ascher and Mark Lutz, Learning Python, OREILLY
 Eric Matthes, Python Crash Course, 2nd Edition: A Hands-On, Project-Based Introduction
to Programming, Starch Pres

Web Links
https://www.tutorialspoint.com/python/index.htm
https://www.python.org/downloads/
https://www.w3schools.in/python/data-types
https://www.programiz.com/python-programming/online-compiler/
https://www.codecademy.com/catalog/language/python

LOVELY PROFESSIONAL UNIVERSITY 49


Notes
UNIT 4 Unit 04: More on OOP Concepts

obj.show()
obj.display()

Summary
 Function overloading is a phenomenon that occurs when several functions with the same
name have different numbers of parameters
 In Python, the most recent definition of a function is taken into account for determining its
validity.
 Built-in classes are supported by Python operators. However, the same operator responds
differently to several types.
 Python refers to class functions that start with a double underscore as special functions.
 Operator overloading is not restricted to arithmetic operators in Python. Additionally, we
can overload comparison operators.
 Any object-oriented programming language has the capability of allowing a subclass or
child class to offer a customised implementation of a method that is already supplied by one
of its super-classes or parent classes.
 Many inheritances are the term used when a class derives from multiple base classes.

Keywords
Operator Overloading: When an operator in Python is overloaded, it signifies that it has additional
meaning in addition to its usual operational meaning.
Multiple Inheritance: Many inheritance is the term used when a class derives from multiple base
classes.
Multilevel Inheritance:When we have a child and grandchild relationship.
Function Overloading: When many functions share the same name but have different numbers of
parameters, this is known as function overloading.
Built-in functions: We have a few special functions in the Python Data Model, and it gives us the
ability to overload the built-in functions. The special function names all start with double
underscores ( ).
Functions:A function is a segment of clean, reusable code that executes a single, connected
operation. A higher level of code reuse and improved application modularity are provided via
functions.
Operator Overloading: Built-in classes are supported by Python operators. However, the same
operator responds differently to several types. For instance, the + operator will combine two lists,
concatenate two strings, or perform arithmetic addition on two numbers.
Method Overriding:Any object-oriented programming language that supports method overriding
enables a subclass or child class to provide a particular implementation of a method that is already
supplied by one of its super-classes or parent classes.

Self Assessment
Q1. Which function overload the + operator?

A. __add__()
B. __plus__()
C. __sum__()

60 LOVELY PROFESSIONAL UNIVERSITY


Notes

Programming in Python

D. None of the above

Q2:Which function overload the == operator?

A. __eq__()
B. __equ__()
C. __equal__()
D. None of the above

Q3: Which function overloads the >> operator?

A. __more__()
B. __gt__()
C. __ge__()
D. None of the above

Q4: Which operator is overloaded by the __or__() function?

A. ||
B. |
C. //
D. /

Q5: Which function overloads the // operator?

A. __div__()
B. __ceildiv__()
C. __floordiv__()
D. __truediv__()

Q6 : Select the valid ways of overloading the operators.

A. Using friend function


B. Using member function
C. Either member function or friend function can be used
D. Operators can’t be overloaded

Q7: Overloading a subprogram allows subprogram to

A. Operate on objects of different types


B. Operate on objects of same name
C. Operate on objects of different name
D. Operate on objects of same types

Q8: What is necessary condition to overload parameters type of a subprogram.

A. The base type of two parameter must differ.


B. The parameter can’t of integer type
C. The parameter must have a different name

LOVELY PROFESSIONAL UNIVERSITY 61


Notes

Unit 04: More on OOP Concepts

D. The base type of two parameter must be same.

Q9: By overloading + operator, it is possible to ________

A. Use binary addition


B. Use arithmetic addition
C. Use it a subtract operator
D. None of the above

Q10: What is correct about overloading + and – operators.

A. They can be defined as binary operators only.


B. They can be defined as unary operators only.
C. They can define as ternary operators only
D. They can be defined as either binary or unary operators.

Q11: Which of the subsequent claims about variable names in Python is true?

A. All variable names must begin with an underscore.


B. Unlimited length
C. The variable name length is a maximum of 2.
D. All of the above

Q12: Which of the following commands the expression with the most precedence?

A. Division
B. Subtraction
C. Power
D. Parentheses

Q13: Which of the following option is not a core data type in the python language?

A. Dictionary
B. Lists
C. Class
D. All of the above

Q14: How to set up Numpy on a computer.

A. install numpy
B. pip install python numpy
C. pip install numpy
D. pip install numpypython

Q15: Which option from the list below best demonstrates how to import the Numpy module
into your programme?

A. import numpy
B. import numpy as np

62 LOVELY PROFESSIONAL UNIVERSITY


Notes

Programming in Python

C. from numpy import *


D. All of the above

Answers for Self Assessment


1. A 2. A 3. D 4. B 5. C

6. C 7. A 8. A 9. A 10. D

11. B 12. D 13. C 14. C 15. D

Review Question
1. What is function overloading. Explain with example.
2. Explain operator overloading with example.
3. What do you understand by method overriding. Explain with example.
4. Explain function overloading with example.
5. What do you understand by type conversion and also explain difference between
overloaded functions and overridden functions?

FurtherReadings
 Mark Lutz,Programming Python: Powerful Object-Oriented Programming, OREILLY
 Wes McKinney, Python for data analysis, OREILLY
 David Ascher and Mark Lutz, Learning Python, OREILLY
 Eric Matthes, Python Crash Course, 2nd Edition: A Hands-On, Project-Based
Introduction to Programming, Starch Pres

Web Links
https://www.tutorialspoint.com/python/index.htm
https://www.python.org/downloads/
https://www.w3schools.in/python/data-types
https://www.programiz.com/python-programming/online-compiler/
https://www.codecademy.com/catalog/language/python

LOVELY PROFESSIONAL UNIVERSITY 63


Notes
Programming in Python UNIT 5
Summary
 When you have finished testing the software, you can turn an assertion on or off as a sanity
check.
 An event that occurs during the execution of a programme and obstructs the regular flow of
the program's instructions is an exception.
 Python uses try and except statements to catch and deal with exceptions.
 Using the raise statement, you can raise exceptions in a number of different ways.
 By deriving classes from the typical built-in exceptions, Python also lets you design your own
exceptions.
 To provide handlers for various exceptions, a try statement may contain more than one except
clause.
 The finally keyword in Python is always invoked following the try and except sections.
 The raise statement enables the programmer to compel the occurrence of a particular
exception. raise's lone argument identifies the exception that should be raised.
 When your programme encounters a problem, Python automatically throws a number of
built-in exceptions (something in the programme goes wrong).
 The finally keyword is available in Python, and it is always used after the try and except
blocks.

Keywords
Exceptions: The finally keyword is available in Python, and it is always used after the try and
except blocks.
try: A try statement in Python can be used to manage exceptions
try catch:The try clause contains the crucial operation that can cause an exception
Arithmetic error: Raised when an error occurs in numeric calculations
Keyerror: Raised when a key does not exist in a dictionary
Runtimeerror: Raised when an error occurs that do not belong to any specific expectations.
Unboundlocalerror: Raised when a local variable is referenced before assignment
Zerodivisionerror: Raised when the second operator in a division is zero
Identation error: Raised when indendation is not correct
Importerror: Raised when an imported module does not exist
AssertionError: Raised when an assert statement fails
AttributeError: Raised when attribute reference or assignment fails
EOFError: Raised when the input() method hits an "end of file" condition (EOF)

NameError: Raised when a variable does not exist


OverflowError: Raised when the result of a numeric calculation is too large
TabError: Raised when indentation consists of tabs or spaces

Self Assessment
1. A try-except block can only contain so many except statements.
A. Zero
B. One

LOVELY PROFESSIONAL UNIVERSITY 71


Notes
Unit 05: Exception Handling
C. More than one
D. More than zero

2. Is the Python code below correct?


try:
#Do something
except:
#Do Something
else:
#Do something

A. No, there is no such thing lese


B. No, else cannot be used with except.
C. No, else must come before except
D. Yes

3. The finally block is executed when?


A. there is no exception
B. there is an exception
C. only if some condition that has been specified is satisfied
D. Always

4. What would the following Python code produce?


def foo ():
try:
print (1)
finally:
print (2)
foo ()

A. 12
B. 1
C. 2
D. 11

5. What occurs when '1' == 1 is put into action?


A. getting a True
B. we receive a False
C. a TypeError happens
D. There is a ValueError.\

6. What type of error is produced in python?


A. Compile time error
B. Run time error
C. Both a and b
D. None of these

72 LOVELY PROFESSIONAL UNIVERSITY


Notes
Programming in Python

7. When a ________ error occurs, the interpreter refuses to run the programme until the error
is fixed; instead, we must save and rerun the programmes.
A. Syntax errors
B. Logical error
C. Runtime error
D. All of the above

8. A Python object called _________ stands for an error.


A. Interpreter
B. Compiler
C. Exception
D. Module

9. An exception is said to have been made when a programme fails to run as


intended___________
A. Created
B. Asserted
C. Triggered
D. Raised

10. When a local or global variable is not defined, it gets raised.


A. NameError
B. ValueError
C. TypeError
D. ZeroDivisionError

11. It is raised when a calculation's outcome is greater than the numeric data type's upper
limit.
A. ZeroDivisonError
B. OverFlowError
C. TypeError
D. ValueError

12. A rule is considered to be broken when


A. Error encountered and exception object is created
B. Runtime system searches for appropriate exception handler
C. Code that is designed to handle exception is executed
D. None of these

13. Exception handling is done in


A. try block
B. except block
C. finally, block
D. else block

LOVELY PROFESSIONAL UNIVERSITY 73


Notes
Unit 05: Exception Handling
14. Which of the following keywords doesn't fall within the category of exception handling?
A. try
B. catch
C. except
D. finally

15. When managing exceptions, certain keywords are utilised.


A. raise, assert, throw, catch
B. try, except, throw, catch
C. try, except, else, finally
D. throw, catch, finally, assert

Answers for SelfAssessment


1. D 2. D 3. D 4. A 5. B

6. C 7. A 8. C 9. D 10. A

11. B 12. C 13. C 14. B 15. C

Review Questions
1. Describe how actually does the python try except clause works.
2. Give example how to catch specific exceptions in python.
3. With example explain raising exception in python.
4. Differentiate between try with else cluse and try with finally clause with example.
5. In Python can a try have multiple except?

Further Readings
 Mark Lutz,Programming Python: Powerful Object-Oriented Programming,
OREILLY
 Wes McKinney, Python for data analysis, OREILLY
 David Ascher and Mark Lutz, Learning Python, OREILLY
 Eric Matthes, Python Crash Course, 2nd Edition: A Hands-On, Project-Based
Introduction to Programming, Starch Pres

Web Links

 https://www.tutorialspoint.com/python/index.htm
 https://www.python.org/downloads/
 https://www.w3schools.in/python/data-types
 https://www.programiz.com/python-programming/online-compiler/
 https://www.codecademy.com/catalog/language/python
 https://www.programiz.com/python-programming/user-defined-exception

74 LOVELY PROFESSIONAL UNIVERSITY


Notes
Programming in Python
UNIT 6
to 10 index(excluded):', 'nhy n')

6.6 Tuple Slicing


Tuple slicing is an option. It functions similarly to how lists and strings do. Several elements can be
obtained through tuple slicing. The slicing operator is also used to accomplish tuple slicing. The
syntax can be used to express the slicing operator.
Syntax:
[start:stop:step]

6.7 Difference between Indexing and Slicing

Indexing Slicing

It only produces 1 item. A new list or tuple is returned.

If you try to utilise an index that is too big, an Out-of-range indices are handled kindly when
IndexError will be thrown. used for slicing.

The list's length cannot be altered by item By designating objects to slicing, we can
assignment during indexing. modify the list's length or even remove items
from it.

Indexing can be given a single element or an A Type Error occurs when we assign a single
iterable. element to slicing. It only permits iterables.

Summary
 In Python, a list is a group of things that can include items of different data types, such as
numeric, character, logical values, etc
 A vector with members that are homogenous, or of the same data type, is referred to as an
array
 With the exception of the fact that it has fewer parameters, this function is comparable to
numpy.array.
 A buffer is treated as a one-dimensional array by this function. To return an ndarray, any
object that exposes the buffer interface is used as an argument
 This function converts any iterable object into an ndarray object. This function returns a
brand-new one-dimensional array.
 Only sequence data types are capable of indexing and slicing. Sequence types maintain the
order in which elements are added, allowing us to retrieve their elements through indexing
and slicing.
 An element of an iterable is said to be "indexed" if it is based on where it is located inside the
iterable.
 We pass a Positive index (that we want to access) in square brackets in this situation. Index
number zero is the first in the list of index numbers. (depicts the start of a string's characters).
 In this kind of indexing, the negative index that we want to access is passed in square
brackets. In this instance, the index number starts at -1.
 Getting a subset of elements from an iterable based on their indices is referred to as "slicing."
 Tuple slicing is an option. It functions similarly to how lists and strings do. Several elements
can be obtained through tuple slicing.

LOVELY PROFESSIONAL UNIVERSITY 83


Notes
Unit 06: Introduction to Numpy

Keywords
append ():Adds an element at the end of the list
clear ():Removes all the elements from the list
copy ():Returns a copy of the list
count ():Returns the number of elements with the specified value
extend ():Add the elements of a list (or any iterable), to the end of the current list
index ():Returns the index of the first element with the specified value
insert ():Adds an element at the specified position
pop ():Removes the element at the specified position
remove ():Removes the first item with the specified value
reverse ():Reverses the order of the list
sort ():Sorts the list

SelfAssessment
1. Which of the ensuing commands will result in the creation of a list?
A. list1 = list()
B. list1 = []
C. list1 = list([1, 2, 3])
D. all of the mentioned

2. What is the output when we execute list(“hello”)?


A. [‘h’, ‘e’, ‘l’, ‘l’, ‘o’]
B. [‘hello’]
C. [‘llo’]
D. [‘olleh’]

3. What is max(list1) if list1 is [2445,133,12454,123]?


A. 2445
B. 133
C. 12454
D. 123

4. What function do we use to shuffle the list, let's say list1?


A. list1.shuffle()
B. shuffle(list1)
C. random.shuffle(list1)
D. random.shuffleList(list1)

5. What is list1[-1] if list1 is [2, 33, 222, 14, 25]?


A. Error
B. None

84 LOVELY PROFESSIONAL UNIVERSITY


Notes
Programming in Python
C. 25
D. 2

6. What does Python's NumPy function do?


A. To do numerical calculations
B. To do scientific computing
C. Both A and B
D. None of the mentioned above

7. What other Python libraries are comparable to Pandas?


A. NPy
B. RPy
C. NumPy
D. none of the mentioned above

8. Which of the following statements about Python's Pip is true?


A. Pip is a standard package management system
B. It is used to install and manage the software packages written in Python
C. Pip can be used to search a Python package
D. All of the mentioned above

9. Arrays in NumPy can be.


A. Indexed
B. Sliced
C. Iterated
D. All of the mentioned above

10. What will happen if you observe the following code and predict the outcome?
import numpy as np
a=np.array([1,2,3,4,5,6])
print(a)

A. [1 2 3 4 5]
B. [1 2 3 4 5 6]
C. [0 1 2 3 4 5 6]
D. None of the mentioned above

11. What will happen if you observe the following code and predict the outcome?
import numpy as np
a = np.array([10, 20, 30, 40])
b = np.array([18, 15, 14])
c = np.array([25, 24, 26, 28, 23])
x, y, z = np.ix_(a, b, c)

LOVELY PROFESSIONAL UNIVERSITY 85


Notes
Unit 06: Introduction to Numpy
A. [[10]]
[[20]]
[[30]]
[[40]]]
B. [[[1]]
[[2]]
[[3]]
[[4]]
C. [[5]]]
[[[18]]
[[15]]
[[[14]]]
D. None of the mentioned above

12. ndim allows us to find:


A. We can determine the array's dimension.
B. array size
C. Matrix operational activities
D. None of the previously mentioned

13. What will the following Python code produce?


import numpy as np
a = np.array([(10,20,30)])
print(a.itemsize)

A. 10
B. 9
C. 8
D. All of the mentioned above

14. Which of the following is the truncation division operator in Python?


A. |
B. //
C. /
D. %

15. Which one of the following is not a keyword in Python language?


A. pass
B. eval
C. assert
D. nonlocal

Answers for SelfAssessment


1. D 2. A 3. C 4. A 5. C

86 LOVELY PROFESSIONAL UNIVERSITY


Notes
Programming in Python

6. C 7. C 8. D 9. D 10. B

11. A 12. A 13. C 14. B 15. B

Review Questions
1. Explain difference between indexing and slicing
2. Differentiate between Arrays and lists with examples.
3. Write down advantages of NumPy arrays compared with lists.
4. Explain using arrays in python with example.
5. Explain copy (), extend (), index (), pop () and remove () method with example.

Further Readings
 Mark Lutz, Programming Python: Powerful Object-Oriented Programming,
OREILLY
 Wes McKinney, Python for data analysis, OREILLY
 David Ascher and Mark Lutz, Learning Python, OREILLY
 Eric Matthes, Python Crash Course, 2nd Edition: A Hands-On, Project-Based
Introduction to Programming, Starch Pres

Web Links

 https://www.tutorialspoint.com/python/index.htm
 https://www.python.org/downloads/
 https://www.w3schools.in/python/data-types
 https://www.programiz.com/python-programming/online-compiler/
 https://www.codecademy.com/catalog/language/python
 https://www.programiz.com/python-programming/user-defined-exception

LOVELY PROFESSIONAL UNIVERSITY 87


UNIT 7 Unit 07: Operations on NumPy Arrays
Notes

% Modulus x%y

** Exponentiation x ** y

// Floor Division x // y

b. Bitwise Operators
To compare (binary) numbers, use the following bitwise operators:

Operator Name Description

& AND if both bits are 1, sets each bit to 1.

| OR if one of two bits is 1, it sets each bit to 1.

^ XOR if just one of two bits is 1, it sets each bit to 1.

~ NOT all the bits are inverted.

<< Zero fill left Pushing zeros in from the right causes a shift to the left, causing
shift the last few bits to disappear.

>> Signed right Push copies of the leftmost bit in from the left to shift right whil
shift e letting the rightmost bits fall off.

c. Relational Operators
The primary purpose of the relational operators, commonly referred to as comparison operators, is
to return either true or false depending on the value of the operands.
The relational operators are listed as follows:

1. <
2. >
3. <=
4. >=
5. ==
6. !=

Summary
 Arrays are not natively supported by Python, although Python Lists can be used in their place
 A unique type of variable called an array has the capacity to store several values at once.
 An array element is referred to by its index number.
 Return the length of an array using the Len () function (the number of elements in an array).
 To iterate over each element of an array, use the for in loop.
 The append () method can be used to include an element in an array.
 The term "broadcasting" describes how Numpy handles arrays of differing dimensions when
performing operations that result in restrictions; the smaller array is broadcast across the
bigger array to ensure that they have similar forms.
 The primary purpose of the relational operators, commonly referred to as comparison
operators, is to return either true or false depending on the value of the operands.
 Python's array module can be imported to generate an array. An array can be created by using
the syntax array (data type, value list), which takes two arguments: a data type and a value
list.

92 LOVELY PROFESSIONAL UNIVERSITY


Notes UNIT 7UNIT 1UNIT 1
Programming in Python
 The Array can have elements added to it by using the built-in insert () function.
 (1)/O Time Complexity (n) (O(1) for inserting elements at the array's end, O(n) for inserting
elements at its start, and O(n) for inserting elements throughout the entire array.

Keywords
append()Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position

remove()Removes the first item with the specified value


reverse()Reverses the order of the list
sort() Sorts the list

Self Assessment
1. What does the following code produce as output?
L = ['d','e','f','g']
print("".join(L))

A. Error
B. None
C. defg
D. ‘d’,’e’,’f’,’g’

2. What does the following code produce as output?


print type(type(int))

A. <type ‘type’>
B. type ‘int’
C. integer
D. 0

3. When a function is declared inside a class, what is called?


A. Function
B. Module
C. Class function
D. Method

4. Which of the following describes how Python's id() function is used?


A. Id returns the identity of the object

LOVELY PROFESSIONAL UNIVERSITY 93


Notes
Unit 07: Operations on NumPy Arrays
B. Id returns the first number in list
C. Id returns the last number in list
D. None

5. To declare an array, you must use


A. Parenthesis ( )
B. Curly brackets { }
C. Pipes | |
D. Brackets [ ]

6. An item's position in an array is known as its


A. Value
B. Location
C. Index
D. Position

7. What else is said to be a FOR-NEXT loop?


A. condition-controlled
B. count-controlled
C. Uncontrolled loop
D. Controlled loop

8. What is the index of the following array's lower bound?


Dim student (24) as string

A. 24
B. 25
C. 23
D. 0

9. In names=[Red, Green, Blue] Index value 1 is?


A. Red
B. Blue
C. 0
D. Green

10. len(names)
A. Finds the length of the list called names
B. Finds the length of the list called len
C. Finds the length of the list called Length
D. None

11. colors = ["Red", "Green", "Blue"]


for x in colors:

94 LOVELY PROFESSIONAL UNIVERSITY


Notes
Programming in Python
print(x)

A. Red
B. Green
C. Red Green Blue
D. Blue

12. Use of pop () method


A. To add an element to an array
B. To remove an element from an array
C. To remove the first occurrence of the specified value
D. None of above.

13. Use of clear () method


A. Remove only first element from the list
B. Removes all the elements from the list
C. Reverse the list
D. None of above

14. What does the following code produce as output?


val1 = 4
val2 = 4
res = val1 + val2
print(res)

A. 88
B. 44
C. 8
D. 4+4

15. What does the following code produce as output?


val1 = 3
val2 = 2
res = val1 // val2
print(res)

A. 1
B. 2
C. 3
D. 0

16. Explain all arithmetic operatorswith example.


17. Explain bitwise operators with example.
18. Explain relational operators with example.
19. What do you understand by Arrays? Explain difference between array and lists.

LOVELY PROFESSIONAL UNIVERSITY 95


UNIT 7UNITUnit107: Operations on NumPy Arrays Notes

20. The term "broadcasting" describes how NumPy handles arrays of differing dimensions
when performing operations that result in restrictions. Explain with example.

Answers for Self Assessment


1. C 2. A 3. D 4. A 5. D

6. C 7. B 8. B 9. D 10. A

11. C 12. B 13. B 14. C 15. A

Further Readings
 Mark Lutz,Programming Python: Powerful Object-Oriented Programming,
OREILLY
 Wes McKinney, Python for data analysis, OREILLY
 David Ascher and Mark Lutz, Learning Python, OREILLY
 Eric Matthes, Python Crash Course, 2nd Edition: A Hands-On, Project-Based
Introduction to Programming, Starch Pres

Web Links

 https://www.tutorialspoint.com/python/index.htm
 https://www.python.org/downloads/
 https://www.w3schools.in/python/data-types
 https://www.programiz.com/python-programming/online-compiler/
 https://www.codecademy.com/catalog/language/python

96 LOVELY PROFESSIONAL UNIVERSITY


UNIT 8 Unit 08: NumPy Functions
Notes

Summary
 Mathematical calculations may occasionally be required when working on certain types of
business or scientific tasks
 The value of numerous constants, including pi and tau, is provided via the math module
 By importing the statistic keyword, Python has the capacity to solve mathematical expressions
and statistical data.
 With the use of an iterator or series, this function determines the arithmetic mean or average
value of the sampled data.
 When there are more even than odd components in the data, this function calculates the lower
of the two middle elements, rather than the median.
 If there are even numbers of items, this function calculates the higher of the two middle
elements in the data; otherwise, it calculates the median of the data.
 NumPy has a number of functions that are relevant to sorting. These sorting functions
implement many sorting algorithms, each of which is distinguished by its execution speed,
worst-case performance, required workspace, and algorithmic stability
 A sorted version of the input array is returned by the sort() function.
 The numpy.argsort() function returns an array of data indices by performing an indirect sort
on the input array along the specified axis.
 Function uses a series of keys to conduct an indirect sort. The keys can be thought of as a
spreadsheet column.

Keywords
numpy.sort(): A sorted version of the input array is returned by the sort() function.
numpy.argsort(): The numpy.argsort() function returns an array of data indices by performing an
indirect sort on the input array along the specified axis. The sorted array is built using this indices
array.
numpy.lexsort(): function uses a series of keys to conduct an indirect sort. The keys can be
thought of as a spreadsheet column. The function provides an array of indices that can be used to
retrieve the sorted data.

numpy.argmax() and numpy.argmin(): These two operations give back the indices of the
highest and lowest elements along the specified axis.

numpy.nonzero():The output of the numpy.nonzero() function is the indexes of the array's non-
zero members.
numpy.where():The where() function returns the indices of input array members that satisfy the
specified criterion.
numpy.extract():The function extract() returns elements that meet any requirement.

Self Assessment
1. What does the following code produce as output?
# Import math Library
import math
print(math.acos(0.65)

A. 0.863211890069541
B. 2.15316056466364

LOVELY PROFESSIONAL UNIVERSITY 109


Notes
Programming in Python
C. 1.5707963267948966
D. 0.0

2. What does the following code produce as output?


# Import statistics Library
import statistics
print(statistics.mean([2, 4, 8, 16, 9, 11, 13]))

A. 7
B. 9
C. 8
D. 0

3. What does the following code produce as output?


# Import statistics Library
import statistics
print(statistics.median([2, 4, 6, 8, 16, 11, 13]))

A. 7
B. 9
C. 8
D. 8.5

4. What does the following code produce as output?


print(math.ceil(2.4))
print(math.ceil(6.3))
print(math.ceil(-4.3))
print(math.ceil(21.6))
print(math.ceil(15.0))

A. 4,7,-4,22,17
B. 4,7,-4,21,15
C. 4,7,-4,22,15
D. 3,7,-4,22,15

5. What does the following code produce as output?


# import math Library
import math
print(math.isfinite(5670))
print(math.isfinite(-46.33))
print(math.isfinite(math.inf))

A. True, True, False


B. False, True, False
C. True, False, False
D. True, True, True

110 LOVELY PROFESSIONAL UNIVERSITY


Notes
Unit 08: NumPy Functions
6. What does the following code produce as output?
# Import statistics Library
import statistics
# Calculate the variance from a sample of data
print(statistics.variance([2, 4, 6, 8, 8, 10]))

A. 7.6666666
B. 8.6666666
C. 9.6666667
D. 7.456789

7. What does the following code produce as output?


# Import statistics Library
import statistics
# Calculate the standard deviation from a sample of data
print(statistics.stdev([2, 4, 6, 8, 10, 12]))

A. 3.7416573867739413
B. 3.8516573867739413
C. 4.7416573867739413
D. 3.9426673867739413

8. What does the following code produce as output?


# Import statistics Library
import statistics
# Calculate the mode
print(statistics.mode([2, 4, 4, 5, 6, 8, 8, 10]))

A. 3
B. 6
C. 5
D. 4

9. What does the following code produce as output?


# Import math Library
import math
# Initialize the number of items to choose from
n=5
# Initialize the number of possibilities to choose
k=4
# Print total number of possible combinations
print (math.comb(n, k))

A. 6
B. 7
C. 5
D. 4

LOVELY PROFESSIONAL UNIVERSITY 111


Notes
Programming in Python

10. What does the following code produce as output?


#Import math Library
import math
#Convert angles from radians to degrees:
print (math.degrees(7.90))
print (math.degrees(-12))

A. 852.63665815335037, -687.5493541569879
B. 352.63665815335037, -687.5493541569879
C. 462.63665815335037, -887.5493541569879
D. 452.63665815335037, -687.5493541569879

11. What does the following code produce as output?


#Import math Library
import math
#Remove - sign of given number
print(math.fabs(-55.34))
print(math.fabs(-6))

A. 55.34, 6.0
B. 54.34,6.0
C. 55.24,6.0
D. None of above
E. Red Green Blue
F. Blue

12. What does the following code produce as output?


# Import math Library
import math
# Return the base-10 logarithm of different numbers
print(math.log10(1.8183))

A. 0.359665538729672
B. 0.269665538729672
C. 0.459665538729672
D. 0.259665538729672

13. What does the following code produce as output?


# Import statistics Library
import statistics
# Calculate the variance of an entire population
print(statistics.pvariance([2, 4, 6, 8, 9, 11]))

A. 10.222222222222223
B. 11.222222222222223
C. 9.222222222222223

112 LOVELY PROFESSIONAL UNIVERSITY


Notes
Unit 08: NumPy Functions
D. 12.222222222222223

14. What does the following code produce as output?


#Import math Library
import math
#find the the greatest common divisor of the two integers
print (math.gcd(4, 5))

A. 1
B. 2
C. 3
D. 4+4

15. What does the following code produce as output?


# Import math Library
import math
# Return the value of 9 raised to the power of 3
print(math.pow(4, 3))1

A. 12
B. 64
C. 444
D. None of above

16. Explain with example function of ceil () and copysign ()


17. Explain power and logarithmic functions
18. Explain trigonometric and angular conversion functions.
19. Explain statistical functions in python.
20. Explain sort, search and count function in python

Answers for Self Assessment


1. A 2. B 3. C 4. D 5. A

6. A 7. A 8. D 9. C 10. D

11. A 12. D 13. C 14. A 15. B

FurtherReadings
 Mark Lutz,Programming Python: Powerful Object-Oriented Programming,
OREILLY
 Wes McKinney, Python for data analysis, OREILLY
 David Ascher and Mark Lutz, Learning Python, OREILLY
 Eric Matthes, Python Crash Course, 2nd Edition: A Hands-On, Project-Based
Introduction to Programming, Starch Pres

LOVELY PROFESSIONAL UNIVERSITY 113


Notes UNIT 9
Programming in Python

# importing pandas package


import pandas as pd

# making data frame from csv file


data = pd.read_csv("nba.csv", index_col
="Name")

# retrieving row by loc method


first = data.loc["Avery Bradley"]
second = data.loc["R.J. Hunter"]

print(first, "\n\n\n", second)

Indexing a DataFrameusing .iloc[ ] :


We can retrieve rows and columns by position using this function. We must give both the desired
places for the desired rows and columns in order to accomplish that. While the df.iloc indexer is
quite similar to df.loc, it only selects integer locations.

Selecting a single row


We can supply a single integer to the.iloc[] function in order to use it to choose a single row.

Program Output

import pandas as pd
# making data frame from csv file
data = pd.read_csv("nba.csv", index_col
="Name")
# retrieving rows by iloc method
row2 = data.iloc[3]
print(row2)

Summary
 A one-dimensional labelled array called a series can store any kind of data (integer, string,
float, python objects, etc.). The term index refers to all of the axis labels.
 The index passed must have the same length as data if the data is an ndarray. If no index
is provided, range(n), where n is the array length, will be used as the default index, which
is [0,1,2,3.. range(len(array))-1].
 The values are identified with their index number if nothing else is supplied. The index of
the first item is 0, that of the second is 1, etc.
 You are able to name your own labels using the index option.
 The term "Comma Separated Values" or CSV. It is the most basic way to save tabular data
as plain text. Because we as data scientists usually use CSV data in our daily work, it is
crucial to know how to work with it.

124 LOVELY PROFESSIONAL UNIVERSITY


Notes
Unit 09: Handling with Pandas
 The list is automatically sorted ascending using the sort() method. Making a function to
select the sorting criteria is another option (s).
 A 2-dimensional labelled data structure called a "DataFrame" has columns that could be of
many sorts. It can be compared to a spreadsheet, SQL table, or dictionary of Series objects.
It is typically the pandas object that is used the most.
 Data is arranged in rows and columns in a data frame, which is a two-dimensional data
structure.

Keywords
Dataframe:A Pandas DataFrame is a two-dimensional data structure having rows and columns,
similar to a two-dimensional array
Series: A Pandas Series resembles a table's column. It is a one-dimensional array that can hold any
kind of data.
Labels:The values are identified with their index number if nothing else is supplied. The index of
the first item is 0, that of the second is 1, etc.
Key/Value Object: When constructing a Series, you can also utilise a key/value object like a
dictionary.
DataFrames:In Pandas, data sets are often multidimensional tables, or "DataFrames."
CSV Files: Using CSV files is an easy approach to store large data sets (comma separated files).
Max_rows:The Pandas option settings control how many rows are returned.
Column_Selection: We have two options for accessing the columns in a Pandas DataFrame in
order to choose one of them.
Row_Selection: Rows from a Pandas DataFrame are retrieved using the DataFrame.loc method.
Indexing Operator: The indexing operator is also used by the.locand.iloc indexers to make
selections.
Dropna(): We used the dropna() method to remove null values from a dataframe. This function
removes rows and columns of datasets containing null values in several ways.

Self Assessment
1. Which of the following is not true about DataFrame?
A. A dataframe can be created by passing dictionaries
B. A dataframe is size immutable
C. A dataframe index can be string
D. A column of dataframe can have different types

2. In Pndas_____________ is used to store data in multiple columns.


A. Series
B. DataFrame
C. Both of the above
D. None of the above

3. A ___________ is a two-dimensional labelled data structure.


A. DataFrame
B. Series
C. List

LOVELY PROFESSIONAL UNIVERSITY 125


Notes
Programming in Python
D. None of the above

4. ____________data structure has both a row and column index


A. DataFrame
B. Series
C. List
D. None of the above

5. Which library is imported for creating DataFrame?


A. Python
B. DataFrame
C. Pandas
D. Random

6. What does the following code produce as output?


Import pandas as pd
D1=pd.DataFrame([1,2,3])

A. 1
B. 4
C. 3
D. 2

7. We can create a DataFrame from ____________


A. Numpy Arrays
B. List of Dictionaries
C. Dictionaries of Lists
D. All of the above

8. Which of the following is used to give user defined column index in DataFrame?
A. index
B. column
C. columns
D. colindex

9. What does the following code produce as output?


#import pandas as pd
LoD = [{‘a’:10, ‘b’:20}, {‘a’:5, ‘b’:10, ‘c’:20}]
D1=pd.DataFrame(LoD)

A. 1
B. 2
C. 3
D. 4

10. In regards to separated value files such as .csv and. tsv, what is the delimiter?
A. Delimiters are not used in separated value files
B. Any character such as the comma (,) or tab (\t) that is used to separate the column data.

126 LOVELY PROFESSIONAL UNIVERSITY


Notes
Unit 09: Handling with Pandas
C. Anywhere the comma (,) character is used in the file
D. Any character such as the comma (,) or tab (\t) that is used to separate the row data

11. In separated value files such as .csv and .tsv, what does the first row in the file typically
contain?
A. The source of the data
B. The column names of the data
C. Notes about the table data
D. The author of the table data

12. When iterating over an object returned from csv.reader(), what is returned with each
iteration?
For example, given the following code block that assumes csv_reader is an object returned
from csv.reader(), what would be printed to the console with each iteration?
for item in csv_reader:
print(item)

A. The full line of the file as a string


B. The column data as a list
C. The row data as a list
D. The individual value data that is separated by the delimiter.

13. When we create Data Frame from Dictionary of List then Keys becomes the ___________
A. Row Labels
B. Column Labels
C. Both of the above
D. None of the above

14. Data Frame created from a single Series has ______ column
# Import math Library
import math
# Return the value of 9 raised to the power of 3
print (math.pow (4, 3))1

A. 1
B. 2
C. n (n is the number of elements in the series)
D. None of above

15. What do you understand by pandas? Explain use of pandas with example along with
installation procedure.
16. What do you understand by CSV file? Explain the steps to read a CSV file.
17. Explain with example creation of DataFrame from dict of ndarrays.
18. Explain column selection and row selection in a DataFrame with examples.
19. Difference between. loc and. iloc function using example.

LOVELY PROFESSIONAL UNIVERSITY 127


Notes
Programming in Python
Answers for Self Assessment
1. B 2. B 3. A 4. A 5. A

6. C 7. A 8. A 9. C 10. C

11. B 12. B 13. C 14. B 15. A

Further Readings
 Mark Lutz,Programming Python: Powerful Object-Oriented Programming,
OREILLY
 Wes McKinney, Python for data analysis, OREILLY
 David Ascher and Mark Lutz, Learning Python, OREILLY
 Eric Matthes, Python Crash Course, 2nd Edition: A Hands-On, Project-Based
Introduction to Programming, Starch Pres

Web Links

 https://www.tutorialspoint.com/python/index.htm
 https://www.python.org/downloads/
 https://www.w3schools.in/python/data-types
 https://www.programiz.com/python-programming/online-compiler/
 https://www.codecademy.com/catalog/language/python

128 LOVELY PROFESSIONAL UNIVERSITY


Notes
Programming in Python
UNIT 10

Looks fantastic! Now let's make sure that none of our sophisticated software misclassifies a
customer name since it isn't capitalised. How to capitalise "Customer Name" correctly is as follows:
INPUT:
data['Customer Name'] = data['Customer Name'].str.title()

OUTPUT:

And there it is—our data collection complete with all the fixings. Or, more accurately, with all the
fixes: To find and remove inaccurate data and normalise the remaining data, we made good use of
logical Python packages.

Summary
 The practise of correcting or deleting inaccurate, damaged, improperly formatted, duplicate,
or incomplete data from a dataset is known as data cleaning.

138 LOVELY PROFESSIONAL UNIVERSITY


Notes
Unit 10: Data Cleanup

 The process of converting data from one format or structure to another is known as data
transformation.
 Remove duplicate or pointless observations as well as undesirable observations from your
dataset. The majority of duplicate observations will occur during data gathering.
 When you measure or transfer data and discover odd naming conventions, typos, or
incorrect capitalization, those are structural errors.
 There will frequently be isolated findings that, at first look, do not seem to fit the data you
are evaluating.
 The main measure of how well-founded and likely accurate a concept, conclusion, or
measurement is called validity.
 Similar to missing data, duplicates are problematic and choke analytics tools. Let's find them
and get rid of them.
 Numerical values that are significantly beyond the statistical norm are considered outliers.
 Another choice will need to be made: to maintain the data in the set while simply dropping
the missing values, or to completely remove the feature (the entire column) because there
are so many missing datapoints that it is unusable for analysis.

Keywords
Data type constraints: Each column's values must belong to a specific data type, such as
Boolean, numeric (integer or real), date, etc.
Range Constraints: Most of the time, dates or numbers must fall inside a specified range. In other
words, they have minimum and/or maximum values that are acceptable.
Unique Constraints: A field, or a group of fields, must be distinct throughout a dataset. The same
social security number cannot be shared by two people, for instance.
Set-Membership Constraints: A set of discrete values or codes is used to generate the values for
each column. A person's sex, for instance, may be Female, Male, or Non-Binary.
Foreign-key Constraints: The more typical case of set membership is this. One table's column
that has distinct values defines the set of values in another table's column. For instance, the "state"
column in a US taxpayer database must be one of the US's recognized states or territories; the list of
acceptable states and territories is kept in a separate State table. Foreign key is a word that was
adopted from relational database terminology.
Regular expression patterns: It may occasionally be necessary to validate text fields in this
manner. For instance, it might be necessary for phone numbers to follow the pattern (999) 999-9999.
Cross-field validation: A certain set of multi-field conditions must be true. For instance, in
laboratory medicine, the differential white blood cell count's component parts must add up to 100.
(Since they are all percentages). A patient's date of discharge from the hospital cannot be earlier
than the date of admission in a hospital database.
Accuracy:The degree of conformity of a measure to a standard or a true value.
Completeness: The extent to which all necessary actions are known. Data cleansing techniques are
usually never able to completely correct incompleteness since they cannot be used to infer
information that was not originally recorded in the data.
Consistency: A set of measures' degree of system-to-system equivalence.
Uniformity: The extent to which a set of data measures are defined across all systems using the
same units of measurement.
Duplicate Detection:An algorithm is needed for duplicate detection in order to determine
whether the same thing is represented twice in the data.

LOVELY PROFESSIONAL UNIVERSITY 139


Notes
Programming in Python

Parsing:A parser determines whether a string of data complies with the specification for permitted
data. This is comparable to how a parser deals with languages and grammars.
Statistical Methods:An expert may discover values that are unexpected and thus incorrect by
analyzing the data using the mean, standard deviation, range, or clustering algorithms.

Self Assessment
1. Which of the following phrases describes the challenge of identifying abstract patterns (or
structures) in unlabeled data?
A. Supervised learning
B. Unsupervised learning
C. Hybrid learning
D. Reinforcement learning

2. Which clustering method calls for the merging approach?


A. Partitioned
B. Naïve Bayes
C. Hierarchical
D. Both A and C

3. Self-organizing maps are another example of a ________ style of learning.


A. Supervised learning
B. Unsupervised learning
C. Missing data imputation
D. Both A & C

4. The total number of neonates in the example of predicting the number of births can be
thought of as the ______________.
A. Features
B. Observation
C. Attribute
D. Outcome

5. Which of the following claims about the classification is accurate?


A. It is a measure of accuracy
B. It is a subdivision of a set
C. It is the task of assigning a classification
D. None of the above

6. How many different sorts of functions are there in data mining?


A. 5
B. 4
C. 2
D. 3

7. The ________________ is the analysis carried out to find the intriguing statistical correlation
between associated -attributes value pairs.

140 LOVELY PROFESSIONAL UNIVERSITY


Notes
Unit 10: Data Cleanup

A. Mining of association
B. Mining of correlation
C. Mining of clusters
D. All of the above

8. Which of the following can be characterized as a data object that deviates from the norm (or
the model of available data)?
A. Evaluation Analysis
B. Outliner Analysis
C. Classification
D. Prediction

9. Which of the following statements about data cleaning is untrue?


A. It refers to the process of data cleaning
B. It refers to the transformation of wrong data into correct data
C. It refers to correcting inconsistent data
D. All of the above

10. The data mining system is categorised using:


A. Database technology
B. Information Science
C. Machine learning
D. All of the above

11. How many different types of data warehousing approaches are there to integrate
heterogeneous databases?
A. 3
B. 4
C. 5
D. 2

12. Select different types of attributes.


A. Nominal
B. Ordinal
C. Interval
D. All of the above

13. Select the correct examples for nominal


A. ID Numbers, eye color, zip codes
B. Rankings, taste of potato chips, grades, height
C. Calendar dates, temperature in Celsius or Fahrenheit
D. The temperature in Kelvin, length time, counts

14. Examples of Ordinal can be


A. ID Numbers, eye color, zip codes
B. Rankings, taste of potato chips, grades, height

LOVELY PROFESSIONAL UNIVERSITY 141


Notes
Programming in Python

C. Calendar dates, temperature in Celsius or Fahrenheit


D. The temperature in Kelvin, length time, counts

15. Example of structured data are


A. Generally
B. Dimensionality
C. Resolution
D. All of the Above

Answers for Self Assessment


1. B 2. C 3. B 4. D 5. B

6. C 7. B 8 B 9 D 10 D

11 A 12 D 13 A 14 B 15 D

Review Questions
1. What do you understand by data cleaning? explain best practices for data cleanig.
2. Explain with code how null values stored in pandas data frames.
3. Difference between structured and unstructured data.
4. What are the effect of missing values in prediction and also explain functions that are used
to handle missing values.
5. Explain following with example.
a. How to see first five rows of Data Frame in python
b. Define data profiling.
c. How t check the class of each variable in pandas DataFrame
d. Write code to see the dimensions of a DataFrame in python.
e. Explain data mining.

FurtherReadings
 Mark Lutz,ProgrammingPython: Powerful Object-Oriented Programming, OREILLY
 Wes McKinney, Python for data analysis, OREILLY
 David Ascher and Mark Lutz, Learning Python, OREILLY
 Eric Matthes, Python Crash Course, 2nd Edition: A Hands-On, Project-Based
Introduction to Programming, Starch Pres

Web Links
https://www.tutorialspoint.com/python/index.htm
https://www.python.org/downloads/
https://www.w3schools.in/python/data-types

142 LOVELY PROFESSIONAL UNIVERSITY


Notes
Unit 10: Data Cleanup

https://www.programiz.com/python-programming/online-compiler/
https://www.codecademy.com/catalog/language/python

LOVELY PROFESSIONAL UNIVERSITY 143


UNIT 11
Notes

Unit 11: Data Visualization

Figure 20 Multiple Histogram

If the stacked parameter is set to True, then many histograms can be piled on top of one another.

Figure 21 Stacking Histogram

Summary
 The human mind processes and comprehends any given data more easily when it is
presented with images, maps, and graphs
 It is used to plot simple graphs like line charts, bar graphs, and so forth.
 It can carry out complicated visualisations with fewer commands and is primarily used for
statistics visualisation.
 An informational graph called a line chart shows data as a collection of dots connected by
straight lines.
 Use the plt.plot method once for each dataset to plot numerous datasets on the same
graph.
 A high-level interface called Seaborn was constructed on top of Matplotlib. It offers
stunning design themes and colour schemes to create graphs that are more appealing.
 Python's Matplotlib toolkit provides a complete tool for building static, animated, and
interactive visualisations.

156 LOVELY PROFESSIONAL UNIVERSITY


Notes

Programming in Python

 Dots are used in scatter plots to show the relationship between variables, which are used
to observe relationships between variables.
 When you have categorical data, a bar graph can be used to display it. A bar graph uses
bars to indicate value on the y-axis and category on the x-axis to plot data.
 A histogram is a bar graph that shows how data changes over time. The range is plotted
along the x-axis, and the height of the data pertaining to a range is plotted along the y-axis.

Keywords
Seaborn:Python has a dataset-oriented library called Seaborn that can be used to create statistical
representations.
Bokeh: For contemporary web browsers, there is a visualisation library called Bokeh.
Altair: A declarative statistical visualisation library for Python is called Altair. The Vega-Lite JSON
specification served as the foundation for Altair's user-friendly, dependable API.
Plotly:A high-level, declarative, interactive, open-source, and browser-based visualisation toolkit
for Python is called plotly.py.
Ggplot: The graphics grammar is implemented in Python by ggplot.
Bar Chart:When comparing metric values between various data subsets, a bar chart is utilised.
Column Chart: When comparing a single category of data between specific sub-items, such as
when comparing revenue between areas, column charts are typically utilised.
Stacked Bar Chart: When comparing the sums of the available groups and the makeup of the
various subgroups, a stacked bar chart is employed.
Pie Chart: Pie charts can be used to determine how much of each component there is in a given
whole.
Area Chart:To monitor changes over time for one or more groups, area charts are employed.
Column Histogram: To view the distribution for a single variable with few data points, column
histograms are utilised.
Scatter Plot:It is possible to use scatter plots to determine the relationships between two variables.
Box Plot:The form of the distribution, its central value, and its variability are displayed using a
box plot.
Waterfall Chart:A waterfall chart can be used to illustrate how a variable's value gradually
changes as a result of increments or decrements.
Venn Diagrams: To visualise the connections between two or three sets of items, utilise Venn
diagrams.

Self Assessment
Q1. Select those which does not visualize the data

A. Charts
B. Shapes
C. Graphs
D. Maps

Q2: Which of the following type of chart is not supported by pyplot?

A. Histogram
B. Boxplot

LOVELY PROFESSIONAL UNIVERSITY 157


Notes

Unit 11: Data Visualization

C. Pie
D. All of the above

Q3: plot which is used to given statistical summary is

A. Bar
B. Line
C. Histogram
D. Box Plot

Q4: To compare data we can use _________ chart

A. Line
B. Bar
C. Pie
D. Scatter

Q5: To import pyplot module we can write

A. Import pyplot as plt


B. Import matplotlib.pyplot
C. Import matplotlib.pyplot as plt
D. Both b and c

Q6: Matplotlib is a ____________ plotting library

A. 1D
B. 2D
C. 3D
D. All of above

Q7: Data __________ refers to graphical representation of data.

A. Visualization
B. Analysis
C. Plotting
D. Handling

Q8: The interface of Matplotlib used for data visualization is

A. Seaborn
B. Anaconda
C. MATLAB
D. Pyplot

Q9: which library is the most used visualization library in python?

A. visual
B. matlibplot

158 LOVELY PROFESSIONAL UNIVERSITY


Notes

Programming in Python

C. matplotlib
D. matlab

Q10: Which function of matplotlib can be used to create a line chart?

A. line
B. plot
C. graph
D. bar

Q11: Which graph should be used if we want to show distribution of elements?

A. pie
B. basemap
C. bar
D. histogram

Q12: which graph should be used If we want to find patterns in data?

A. bar
B. histogram
C. scatterplots
D. basemap

Q13: Which of the following command is correct to install matplotlib?

A. Pip install matplot


B. Pipe install matplot
C. Pip install matplotlib
D. None of the above

Q14: __________ function of the pyplot is used to create a figure/chart/plot.

A. show()
B. plotting()
C. plot()
D. plots()

Q15: A figure/chart contains

A. Plotting area
B. Legend
C. Axis labels
D. All of the above

LOVELY PROFESSIONAL UNIVERSITY 159


Notes

Unit 11: Data Visualization

Answers for Self Assessment


1. B 2. D 3. D 4. B 5. D

6. B 7. A 8 D 9 C 10 D

11 D 12 C 13 C 14 C 15 D

Review Questions
1. What is data visulaizations? Write down benefits of Data Visualization.
2. Write down difference between Matplotlib and Seaborn.
3. Explain Line chart with example.
4. What do you understand by seaborn. Write down command to install seaborn. Explain use
of seaborn with example.
5. Explain difference between scatter plot, bar graph and histogram.

FurtherReadings
 Maheshwari, Anil. Big Data. McGraw-Hill Education, 2019.
 Mayer-Schonberger, Viktor; Cukier, Kenneth (2013). Big Data: A Revolution That
Will Transform How We Live, Work, and Think . Houghton Mifflin Harcourt.
 McKinsey Global Institute Report (2011). Big Data: The Next Frontier For
Innovation, Competition, and Productivity. Mckinsey.com
 Marz, Nathan, and James Warren (2015). Big Data: Principles and Best Practices of
Scalable Realtime Data Systems. Manning Publications.
 Sandy Ryza, Uri Laserson et.al (2014). Advanced-Analytics-with-Spark. OReilley.
White, Tom (2014). Mastering Hadoop. OReilley.

Web Links
1. Apache Hadoop resources: https://hadoop.apache.org/docs/r2.7.2/
2. Apache HDFS: https://hadoop.apache.org/docs/r1.2.1/hdfs_design.html
3. Hadoop API site: http://hadoop.apache.org/docs/current/api/
4. NoSQL databases: http://nosql-database.org/
5. Apache Spark: http://spark.apache.org/docs/latest/

6. Tutorials on Big Data technologies: https://www.tutorialspoint.com/


7. https://www.tutorialspoint.com/hadoop/hadoop_multi_node_cluster.htm

160 LOVELY PROFESSIONAL UNIVERSITY


Notes

UNIT 12 Unit 12: Data Visualization

and vertical graphs of the bars are possible. The comparisons between the distinct categories are
shown in a bar chart. The exact categories under comparison are shown by one of the plot's axes,
while the measured values associated with those categories are represented by the other axis.

KDEPLOT: Kdeplot, also known as a Kernel Distribution Estimation Plot, is a graphical


representation of the probability density function of continuous or non-parametric data variables; it
can be used to plot either a single variable or a number of variables simultaneously. We may create
a Kdeplot with various capabilities added to it using the Python Seaborn module.

Summary
 A package called Seaborn uses Matplotlib as its foundation to plot graphs. In order to see
random distributions, it will be used.
 The statistical link between the data points is depicted using relational graphs. Because it
enables humans to recognise trends and patterns in data, visualisation is essential.
 Histograms are plotted using the seaborn dist plot, as well as the kdeplot and rugplot
variants.
 Another very simple plot is the lmplot. It displays a line denoting a linear regression model
together with data points in a 2D space, and the labels x and y can be set to represent the
horizontal and vertical axes, respectively.
 Data is graphically represented in data visualisation. It facilitates data analysis and
forecasting by breaking down a large dataset into manageable graphs.
 Matplotlib is used to create simple graphs. Bar graphs, histograms, pie charts, scatter plots,
lines, and other visual representations of data are used to visualize datasets.
 Data visualisation patterns and graphs can be found throughout Seaborn. Interesting themes
are employed.
 The visual presentation of data is known as data visualisation. . Because of the excellent
ecosystem of Python packages focused on data, it is crucial for data analysis.
 Pandas provide tools for processing and cleaning up your data. It is the most widely used
Python data analysis library.
 Python's Seaborn visualisation module is fantastic for plotting statistical visualisations. It is
constructed on top of the Matplotlib toolkit and is tightly integrated with the Pandas data
structures.
 The seaborn boxplot has a very simple structure. Distributions are represented visually
using boxplots.
 A point plot uses the position of the dot to indicate an estimate of the central tendency for a
numerical variable, and error bars are used to show the degree of uncertainty surrounding
that estimate. For comparisons between various levels of one or more categorical variables,
point plots may be more helpful than bar plots.
 A violin plot and a box and whisker plot serve the same purpose. In order to allow for
comparison, it displays the distribution of quantitative data across a number of levels of one
(or more) categorical variables.
 The Seaborn swarmplot is presumably similar to the stripplot, with the exception that the
points are adjusted to avoid overlap in order to better depict the distribution of values.
 The KNN algorithm, also referred to as K-nearest neighbor, is a non-parametric algorithm
that groups data points according to their proximity and association with other pieces of
available information.

LOVELY PROFESSIONAL UNIVERSITY 171


Notes

Programming in Python

Keywords
Relational plots: This type of graphic is used to see how two variables are related.
Categorical plots: This graphic discusses categorical variables and the visualization of them.
Distribution Plots: Plots used to examine univariate and bivariate distributions include
distribution plots.
Regression plots: The main purpose of the regression plots in Seaborn is to provide a visual aid
that highlights patterns in a dataset during exploratory data analysis.
Scatter Plots: Plots in a matrix An array of scatterplots makes up a matrix plot.
Multi-plot grids: Drawing numerous instances of the same plot on various subsets of the dataset
is a helpful strategy.
Visualizations:Data is graphically represented in data visualisation. It facilitates data analysis and
forecasting by breaking down a large dataset into manageable graphs.
Pandas and Seaborn: Pandas and Seaborn, makes importing and analysing data more simpler.
Scatter:A scatterplot can be used in conjunction with several semantic groups to aid in clear
understanding of a graph.

Box Plot:A boxplot may also be referred to as a box-and-whisker plot. Any box displays the
dataset's quartiles, and the whiskers extend to display the remainder of the distribution.The
boxplot plot is related with the boxplot() method.

Point plot: A point plot uses the position of the dot to indicate an estimate of the central tendency
for a numerical variable, and error bars are used to show the degree of uncertainty surrounding
that estimate

Self Assessment
Q1. Series and DataFrame's plot function is only a basic wrapper over _____________

A. gplt.plot()
B. plt.plot()
C. plt.plotgraph()
D. none of the mentioned

Q2. Please specify the ideal kind keyword combination for graph plotting.

A. ‘hist’ for histogram


B. ‘box’ for boxplot
C. ‘area’ for area plots
D. all of the mentioned

Q3. Which of the following values does the kind barplot keyword provide?

A. Bar
B. Kde
C. Hexbin
D. none of the mentioned

Q4. By utilising the _________ method in pandas.tools.plotting, you may produce a scatter plot
matrix.

172 LOVELY PROFESSIONAL UNIVERSITY


Notes

Unit 12: Data Visualization

A. sca_matrix
B. scatter_matrix
C. DataFrame.plot
D. all of the mentioned

Q5: Indicate the incorrect kind keyword combination for graph plotting.

A. For scatter plots, use "scatter"


B. "kde" for bin plots with hexagonal axes
C. "pie" for plots of pie
D. None of the previously listed

Q6. Which of the following plots are used to check if a data set or time series is random?

A. Lag
B. Random
C. Lead
D. None of the mentioned

Q7: Which of the following does not visualize data.

A. Charts
B. Maps
C. Shapes
D. Graphs

Q8. Which of the chart is not supported by pyplot?

A. Histogram
B. Boxplot
C. Pie
D. All are correct

Q9: To display histogram with well-defined edge we can write

A. df.plot(type=’hist’, edge=’red’)
B. df.plot(type=’hist’, edgecolor=’red’)
C. df.plot(type=’hist’, line=’red’)
D. df.plot(type=’hist’, linecolor=’red’)

Q10: Plot which is used to given statistical summary is


A. Bar
B. Line
C. Histogram
D. Box Plot

Q11: Which of the following is not the parameter of pyplot’s plot() method.
A. Marker

LOVELY PROFESSIONAL UNIVERSITY 173


Notes

Programming in Python

B. Lineheight
C. Linestyle
D. Color

Q12: To compare data, we can use ________ chart.

A. Line
B. Bar
C. Pie
D. Scatter

Q13: Which of the following chart element is used to identify data series by its color patterns.

A. Chart title
B. Legend
C. Marker
D. Data Labels

Q14: Matplotlib is _____________ plotting library.

A. 1D
B. 2D
C. 3D
D. All of the above

Q15: Data ________ refers to graphical representation of data.

A. Visualisation
B. Analysis
C. Plotting
D. Handling

Answers for Self Assessment


1. B 2. D 3. A 4. D 5. B

6. A 7. C 8. C 9. B 10. D

11. B 12. B 13. B 14. B 15. A

Review Questions

FurtherReadings
 Mark Lutz,Programming Python: Powerful Object-Oriented Programming, OREILLY

174 LOVELY PROFESSIONAL UNIVERSITY


Notes

Unit 12: Data Visualization

 Wes McKinney, Python for data analysis, OREILLY


 David Ascher and Mark Lutz, Learning Python, OREILLY
 Eric Matthes, Python Crash Course, 2nd Edition: A Hands-On, Project-Based
Introduction to Programming, Starch Pres

Web Links
https://www.tutorialspoint.com/python/index.htm
https://www.python.org/downloads/
https://www.w3schools.in/python/data-types
https://www.programiz.com/python-programming/online-compiler/
https://www.codecademy.com/catalog/language/python

LOVELY PROFESSIONAL UNIVERSITY 175


Notes
UNIT 13 Unit 13: OOP Concepts

Object-oriented Programming Procedural Programming

The approach to addressing problems that A list of instructions is used in procedural


uses objects for computation is called object- programming to perform calculations in
oriented programming. stages.

It makes development and upkeep simpler. When a project grows in scope, maintaining
the codes is difficult in procedural
programming.

It replicates the thing in the actual world. It doesn't represent reality in any way. It
Therefore, oops makes it simple to tackle operates using detailed instructions broken
difficulties in the actual world. down into smaller units called functions.

It offers data concealment. Consequently, it Because procedural languages don't offer a


is safer than procedural languages. Private suitable method for data binding, they are less
information is not accessible from anyplace. secure.

C++, Java, .Net, Python, C#, and other object- Procedural languages include C, Fortran,
oriented programming languages are Pascal, VB, and others.
examples.

Summary
 The Python programming style known as object-oriented programming (OOPs) makes use
of objects and classes.
 A class is a group of related items. The models or prototypes used to generate objects are
included in classes.
 The object is an entity that is connected to a state and activity. Any physical device, such as a
mouse, keyboard, chair, table, pen, etc., may be used.
 The constructors in Java and C++ are comparable to the __init__ method. As soon as a class
object is created, it is executed.
 A function connected to an object is the method. A method is not specific to class instances
in Python. Any sort of object may have methods.
 The capacity of one class to derive or inherit properties from another class is known as
inheritance.
 Simply put, polymorphism means having multiple forms. For instance, utilising
polymorphism, we can answer the question of whether the given species of birds fly or not
using just one function
 Both data abstraction and encapsulation are frequently used interchangeably. Since data
abstraction is accomplished by encapsulation, the two terms are almost synonymous
 One of the core ideas in object-oriented programming is encapsulation (OOP). It explains the
concept of data wrapping and the techniques that operate on data as a single unit.
 The approach to addressing problems that uses objects for computation is called object-
oriented programming.
 A list of instructions is used in procedural programming to perform calculations in stages

184 LOVELY PROFESSIONAL UNIVERSITY


Notes
Programming in Python

Keywords
OOPS: Object-oriented programming is known as OOP. While object-oriented programming
involves constructing objects that include both data and methods, procedural programming
involves developing procedures or methods that perform actions on the data.

Class: Python is an object oriented programming language. Almost everything in Python is an


object, with its properties and methods. A Class is like an object constructor, or a "blueprint" for
creating objects

The __init__method: All classes have a function called __init__(), which is always executed when
the class is being initiated.

The __str__function: What should be returned when the class object is rendered as a string is
determined by the __str__() function.

Objects methods: Methods can also be found in objects. Object-specific functions are called
methods in an object.

Self-Parameter: To access class-specific variables, use the self parameter, which is a reference to
the currently running instance of the class.

Del:Using the del keyword, properties on objects can be deleted.


Pass statement: Although class definitions cannot be empty, if for some reason you have one that
is empty, add the pass statement to prevent an error.

Inheritance: By using inheritance, we may create a class that has all the methods and
attributes of another class.
Parent class:The class being inherited from, often known as the base class, is the parent class.
Child class:The class that inherits from another class is referred to as a child class or derived class.
Super Function:The super() function in Python allows a descendant class to inherit all of its
parent's methods and properties.

Self Assessment
Q1. Which option best encapsulates inheritance?

A. Ability of a class to include methods from other classes in its definition


B. Techniques for grouping instance variables and methods to limit access to certain class
members
C. A focus on variables and passing variables to functions
D. Enables the use of sophisticated software that is well-designed and flexible.

Q2. Which of the following claims about inheritance is false?

A. A class's protected members may be inherited.


B. The class that inherits is known as a subclass.
C. A class's private members can be accessed and inherited.
D. One characteristic of OOP is inheritance
.
Q3. What line of code should you write to activate the __init__ method in A from B if B is a
subclass of A?

LOVELY PROFESSIONAL UNIVERSITY 185


Notes

Unit 13: OOP Concepts

A. A.__init__(self)
B. B.__init__(self)
C. A.__init__(B)
D. B.__init__(A)
Q4: What function type is a built-in in the context of classes?

A. Identifies the name of any value's object.


B. Identifies any value's class name.
C. Determines a value's class description
D. Identifies any value's file name

Q5: What one of the following is not an inheritance type?

A. Double-level
B. Multi-level
C. Single-level
D. Multiple

Q6: Which of these is not one of OOP's core characteristics?

A. Encapsulation
B. Inheritance
C. Instantiation
D. Polymorphism

Q7: Which of the following definitions best describes encapsulation?

A. The capacity of a class to derive individuals from other classes as part of its own definition.
B. Techniques for combining instance variables and methods to limit access to specific class
members
C. focuses on supplying parameters to functions and variables.
D. enables the use of sophisticated software that is well-designed and flexible.

Q8: Define Overriding.

A. Overriding can occur in the case of inheritance in class


B. It is a process of redefining inherited method in child class.
C. It is a magic method in python.
D. None of these

Q9: _____________ developed python language

A. Albert Einstein
B. Guido Van Rossum
C. Guido Evan
D. None of these

Q10: What year was the Python programming language created?

186 LOVELY PROFESSIONAL UNIVERSITY


Notes
Programming in Python

A. 1975
B. 1989
C. 1972
D. 1990
Q11: Which of the following commands the expression with the most precedence?

A. Addition
B. Subtraction
C. Parentheses
D. Power

Q12: Of the following, which best describes abstraction?

A. Hiding the execution


B. displaying crucial information
C. Hiding the important data
D. Hiding the implementation and showing only the features

Q13: A class is an ____________ abstraction.

A. Object
B. Logical
C. Real
D. Hypothetical

Q14: Abstraction can be used for _______________.

A. Control and data.


B. Only data
C. Only control
D. Classes

Q15: Which of the following can be considered a combination of data abstraction and
programming?

A. Class
B. Object
C. Inheritance
D. Interfaces

Answer for Self Assessment


l. A 2. C 3. A 4. B 5. A

6. C 7. B 8. B 9. B 10. B

11. C 12. D 13. B 14. A 15. B

LOVELY PROFESSIONAL UNIVERSITY 187


Notes

Unit 13: OOP Concepts

Review Questions
1. What do you understand by OOPS? Write down the code to make a python class that si
empty.
2. Define Objects. Write down example to create an object with methods.
3. What do you understand by inheritance and also define types of inheritance.
4. Write down difference between Single level inheritance, multilevel inheritance and multiple
inheritance.
5. Define Polymorphism. Write down python code that define use of polymorphism.
6. What do you understand by Encapsulation? Write down python program to demonstrate
private members.
7. Write down difference between object-oriented programming and procedural
programming.

FurtherReadings
 Mark Lutz,Programming Python: Powerful Object-Oriented Programming, OREILLY
 Wes McKinney, Python for data analysis, OREILLY
 David Ascher and Mark Lutz, Learning Python, OREILLY
 Eric Matthes, Python Crash Course, 2nd Edition: A Hands-On, Project-Based Introduction
to Programming, Starch Pres

Web Links
https://www.tutorialspoint.com/python/index.htm
https://www.python.org/downloads/
https://www.w3schools.in/python/data-types
https://www.programiz.com/python-programming/online-compiler/
https://www.codecademy.com/catalog/language/python

188 LOVELY PROFESSIONAL UNIVERSITY


Notes
Programming in Python
UNIT 14
 uses an iterative technique to choose the best value for K center points or centroids.
 each data point is matched with the nearest k-center. A cluster is formed by the data points
that are close to a specific k-center.
As a result, each cluster is distinct from the others and contains data points with some
commonality.
The K-means Clustering Algorithm is explained in the diagram below:

Figure 8 K-Means Algorithm

How Does K-Means Algorithm Work?


The following stages illustrate how the K-Means algorithm functions:
Step 1: To determine the number of clusters, choose K.
Step 2: Pick K locations or centroids at random. (It might not be the supplied dataset.)
Step 3: Assign each data point to its nearest centroid, which will create the K clusters that have been
predetermined.
Step 4: Determine the variance and relocate each cluster's centroid.
Step 5: Re-assign each data point to the new centroid of each cluster by repeating the third step.
Step 6: Move to step 4 if there is a reassignment; otherwise, go to FINISH.
Step 7: The finished model

Summary
 The field of study known as machine learning enables computers to learn without being
explicitly programmed.
 Astrategy for predicting a response based on a single feature is simple linear regression.
 A subset of machine learning and artificial intelligence is supervised learning, commonly
referred to as supervised machine learning. It is distinguished by the way it trains computers
to accurately classify data or predict outcomes using labelled datasets.
 In order to accurately classify test data into different categories, classification uses an
algorithm.
 To comprehend the relationship between dependent and independent variables, regression is
used.
 Neural networks process training data by simulating the connectivity of the human brain
through layers of nodes, which is mostly used for deep learning algorithms.

200 LOVELY PROFESSIONAL UNIVERSITY


Notes
Unit 14 : Machine Learning Algorithms

 A classification method known as Naive Bayes adopts the idea of Class Conditional
Independence from the Bayes Theorem.
 In order to anticipate future results, linear regression is frequently employed to determine the
relationship between a dependent variable and one or more independent variables.
 While logistical regression is used when the dependent variable is categorical, or has binary
outputs, such as "true" and "false" or "yes" and "no," linear regression is used when the
dependent variable is continuous.
 Vladimir Vapnik created the well-known supervised learning model known as the support
vector machine, which is used for both data classification and regression.
 The KNN algorithm, also referred to as K-nearest neighbor, is a non-parametric algorithm that
groups data points according to their proximity and association with other pieces of available
information.

Keywords
Linear Regression: When modelling the relationship between a scalar answer and one or more
explanatory variables in statistics, linear regression is a linear method.
Linearity:This indicates that the parameters (regression coefficients) and predictor variables are
combined linearly to produce the mean of the response variable.
Constant variance: This translates to the fact that the variance of the errors is independent of the
values of the predictor variables. Therefore, regardless of how big or small the responses are, the
variability of the responses for given fixed values of the predictors is the same.
Independence of Errors:This assumes that the errors of the response variables are uncorrelated
with each other.
K Nearest Neighbor: One of the simplest Machine Learning algorithms based on the Supervised
Learning technique is K-Nearest Neighbor.
Lazy Learner Algorithm: It is also known as a lazy learner algorithm since it saves the training
dataset rather than learning from it immediately. Instead, it uses the dataset to perform an action
when classifying data.
Euclidean Algorithm:The distance between two points, which we have already examined in
geometry, is known as the Euclidean distance.
Decision Trees:A non-parametric supervised learning technique for classification and regression
is called a decision tree (DT). The objective is to learn straightforward decision rules derived from
the data features in order to build a model that predicts the value of a target variable.
Random Forests: Leo Breiman and Adele Cutler are the creators of the widely used machine
learning technique known as random forest, which mixes the output of various decision trees to
produce a single outcome.
K Means Clustering: The goal of k-means clustering, a vector quantization technique that
originated in signal processing, is to divide n observations into k clusters, where each observation
belongs to the cluster that has the closest mean (also known as the cluster centroid or cluster
centre), which serves as a prototype for the cluster.
K Medoids: K-medoids, also known as Partitioning Around Medoids, or PAM, minimises the sum
of distances for any given distance function by using the medoid rather than the mean.
Principal Component Analysis:Principal component analysis provides the k-means clustering's
relaxed solution, which is determined by the cluster indicators (PCA)
K

Self Assessment
1. Choose the item from the list below that is not a kind of learning.
A. Semi supervisedunsupervisedlearning

LOVELY PROFESSIONAL UNIVERSITY 201


Notes
Programming in Python

B. Supervised learning
C. Unsupervised Learning
D. Reinforcement Learning

2. What is the term for the application of machine learning techniques to a big database?
A. Supervised learning
B. Unsupervised Learning
C. Reinforcement Learning
D. Data mining

3. Machine learning approaches can be traditionally categorized into ______ categories


A. 2
B. 3
C. 4
D. 5

4. The following effects occur as the number of features increases:


A. longer computation times
B. more complex models
C. worse learning accuracy
D. all of the above.

5. The k-means algorithm is a


A. Supervised learning algorithm
B. Unsupervised learning algorithm
C. Semi-supervised learning algorithm
D. Weakly supervised learning algorithm

6. We have a model for unsupervised learning called.


A. interactive
B. predictive
C. descriptive
D. prescriptive

7. Any machine learning model's success Hinges on the engineering of a good feature space.
A. Pre-requisite
B. Process
C. Objective
D. None of the above

8. An example would be determining whether a tumour is benign or malignant.


A. Unsupervised Learning
B. Supervised Regression Problem
C. Supervised Classification Problem
D. Categorical Attribute

202 LOVELY PROFESSIONAL UNIVERSITY


Notes
Unit 14 : Machine Learning Algorithms

9. This is a reference to the adjustments made to the detected data before to feeding it to the
algorithm.
A. Problem Identification
B. Identification of Required Data
C. Data Pre-processing
D. Definition of Training Data Set

10. Which of the following is true about SVM?


A. It is useful only in high-dimensional spaces
B. It requires less memory
C. SVM does not perform well when we have a large data set
D. SVM performs well when we have a large data set

11. Which of the following kNN choices would you take into account if there are a lot of
sounds in the data?
A. Increase the value of k
B. Decrease the value of k
C. Noise does not depend on k
D. k = 0

12. Decision tree defined as


A. Flow-Chart
B. Structure in which internal node represents test on an attribute, each branch represents
outcome of test and each leaf node represents class label.
C. Flow-Chart & Structure in which internal node represents test on an attribute, each branch
represents outcome of test and each leaf node represents class label.
D. None of the mentioned

13. Choose from the following that are Decision Tree nodes?
A. Decision Nodes
B. End Nodes
C. Chance Nodes
D. All of the mentioned

14. Decision Nodes are depicted by


A. Disks
B. Squares
C. Circles
D. Triangles

15. Which benefit(s) of the following apply to decision trees?


A. Possible Scenarios can be added
B. Use a white box model, If given result is provided by a model
C. Worst, best and expected values can be determined for different scenarios
D. All of the mentioned

LOVELY PROFESSIONAL UNIVERSITY 203


Notes
Programming in Python

Answers for Self Assessment


1. A 2. D 3. B 4. D 5. B

6. C 7. A 8. C 9. C 10. D

11. A 12. C 13. D 14. B 15. D

Review Question

Further Readings
 Mark Lutz,Programming Python: Powerful Object-Oriented Programming,
OREILLY
 Wes McKinney, Python for data analysis, OREILLY
 David Ascher and Mark Lutz, Learning Python, OREILLY
 Eric Matthes, Python Crash Course, 2nd Edition: A Hands-On, Project-Based
Introduction to Programming, Starch Pres

Web Links
 https://www.tutorialspoint.com/python/index.htm
 https://www.python.org/downloads/
 https://www.w3schools.in/python/data-types
 https://www.programiz.com/python-programming/online-compiler/
 https://www.codecademy.com/catalog/language/python

204 LOVELY PROFESSIONAL UNIVERSITY

You might also like