Ecap776 Programming in Python MCQ
Ecap776 Programming in Python MCQ
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.
Self Assessment
Q1: Who was the Python programming language's creator?
A. Mark
B. Guido can Rossum
C. Alfred novel
D. Ralf Kleinberg
A. Structural programming
B. Object-oriented programming
C. Functional programming
D. All of the above
A. .ps
B. .pyth
C. .py
D. .thon
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. */
A. python -version
B. python -v
C. python -V
D. None of above
Programming in Python
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
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
A. C++
B. C
C. Java
D. None of these
6. B 7. C 8. D 9. B 10. B
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
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 ([]).
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
A. od Mor
B. od Morn
C. odMor
D. oodMor
A. This Is my File
B. ThIsis my File
C. ThIs Is my FIle
D. ThIs Is my File
A. 81367
B. Error
C. 1367
D. 8 Error
A. 13
B. 14
C. 15
D. 16
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
A. 4
B. 5
C. 3
D. 9
Programming in Python
A. <class ‘list’>
B. <class ‘tuple’>
C. <class ‘boolean’>
D. None of above
A. {‘apple’,‘banana’,’cherry’,’apple’}
B. {‘banana’,’cherry’,’apple’,’apple’}
C. {‘banana’,’apple’}
D. {‘banana’,’cherry’,’apple’}
A. D1601
B. Error
C. String not allowed
D. Type incompatible
A. Green
B. Burnt sienna
C. Blue
D. Red
A. del dict
B. Del dictionary
C. rmvdict
D. remove dictionary
6. C 7. A 8. C 9. B 10. D
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
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.
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
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.
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.
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. 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. Double-level
B. Multi-level
C. Single-level
D. Multiple
A. Encapsulation
B. Inheritance
C. Instantiation
D. Polymorphism
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.
A. Albert Einstein
B. Guido Van Rossum
C. Guido Evan
D. None of these
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
A. Object
B. Logical
C. Real
D. Hypothetical
Q15: Which of the following can be considered a combination of data abstraction and
programming?
A. Class
B. Object
C. Inheritance
D. Interfaces
6. C 7. B 8. B 9. B 10. B
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
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__()
Programming in Python
A. __eq__()
B. __equ__()
C. __equal__()
D. None of the above
A. __more__()
B. __gt__()
C. __ge__()
D. None of the above
A. ||
B. |
C. //
D. /
A. __div__()
B. __ceildiv__()
C. __floordiv__()
D. __truediv__()
Q11: Which of the subsequent claims about variable names in Python is true?
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
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
Programming in Python
6. C 7. A 8. A 9. A 10. 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
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)
Self Assessment
1. A try-except block can only contain so many except statements.
A. Zero
B. One
A. 12
B. 1
C. 2
D. 11
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
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
6. C 7. A 8. C 9. D 10. A
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
Indexing Slicing
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.
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
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)
A. 10
B. 9
C. 8
D. All of the mentioned above
6. C 7. C 8. D 9. D 10. 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
% Modulus x%y
** Exponentiation x ** y
// Floor Division x // y
b. Bitwise Operators
To compare (binary) numbers, use the following bitwise operators:
<< 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.
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
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’
A. <type ‘type’>
B. type ‘int’
C. integer
D. 0
A. 24
B. 25
C. 23
D. 0
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
A. Red
B. Green
C. Red Green Blue
D. Blue
A. 88
B. 44
C. 8
D. 4+4
A. 1
B. 2
C. 3
D. 0
20. The term "broadcasting" describes how NumPy handles arrays of differing dimensions
when performing operations that result in restrictions. Explain with example.
6. C 7. B 8. B 9. D 10. 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
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
A. 7
B. 9
C. 8
D. 0
A. 7
B. 9
C. 8
D. 8.5
A. 4,7,-4,22,17
B. 4,7,-4,21,15
C. 4,7,-4,22,15
D. 3,7,-4,22,15
A. 7.6666666
B. 8.6666666
C. 9.6666667
D. 7.456789
A. 3.7416573867739413
B. 3.8516573867739413
C. 4.7416573867739413
D. 3.9426673867739413
A. 3
B. 6
C. 5
D. 4
A. 6
B. 7
C. 5
D. 4
A. 852.63665815335037, -687.5493541569879
B. 352.63665815335037, -687.5493541569879
C. 462.63665815335037, -887.5493541569879
D. 452.63665815335037, -687.5493541569879
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
A. 0.359665538729672
B. 0.269665538729672
C. 0.459665538729672
D. 0.259665538729672
A. 10.222222222222223
B. 11.222222222222223
C. 9.222222222222223
A. 1
B. 2
C. 3
D. 4+4
A. 12
B. 64
C. 444
D. None of above
6. A 7. A 8. D 9. C 10. D
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
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.
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
A. 1
B. 4
C. 3
D. 2
8. Which of the following is used to give user defined column index in DataFrame?
A. index
B. column
C. columns
D. colindex
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.
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)
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.
6. C 7. A 8. A 9. C 10. C
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
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.
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.
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
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
7. The ________________ is the analysis carried out to find the intriguing statistical correlation
between associated -attributes value pairs.
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
11. How many different types of data warehousing approaches are there to integrate
heterogeneous databases?
A. 3
B. 4
C. 5
D. 2
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
https://www.programiz.com/python-programming/online-compiler/
https://www.codecademy.com/catalog/language/python
If the stacked parameter is set to True, then many histograms can be piled on top of one another.
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.
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
A. Histogram
B. Boxplot
C. Pie
D. All of the above
A. Bar
B. Line
C. Histogram
D. Box Plot
A. Line
B. Bar
C. Pie
D. Scatter
A. 1D
B. 2D
C. 3D
D. All of above
A. Visualization
B. Analysis
C. Plotting
D. Handling
A. Seaborn
B. Anaconda
C. MATLAB
D. Pyplot
A. visual
B. matlibplot
Programming in Python
C. matplotlib
D. matlab
A. line
B. plot
C. graph
D. bar
A. pie
B. basemap
C. bar
D. histogram
A. bar
B. histogram
C. scatterplots
D. basemap
A. show()
B. plotting()
C. plot()
D. plots()
A. Plotting area
B. Legend
C. Axis labels
D. All of the above
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/
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.
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.
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.
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.
A. sca_matrix
B. scatter_matrix
C. DataFrame.plot
D. all of the mentioned
Q5: Indicate the incorrect kind keyword combination for graph plotting.
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
A. Charts
B. Maps
C. Shapes
D. Graphs
A. Histogram
B. Boxplot
C. Pie
D. All are correct
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’)
Q11: Which of the following is not the parameter of pyplot’s plot() method.
A. Marker
Programming in Python
B. Lineheight
C. Linestyle
D. Color
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
A. 1D
B. 2D
C. 3D
D. All of the above
A. Visualisation
B. Analysis
C. Plotting
D. Handling
6. A 7. C 8. C 9. B 10. D
Review Questions
FurtherReadings
Mark Lutz,Programming Python: Powerful Object-Oriented Programming, OREILLY
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
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.
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
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.
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.
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. 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. Double-level
B. Multi-level
C. Single-level
D. Multiple
A. Encapsulation
B. Inheritance
C. Instantiation
D. Polymorphism
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.
A. Albert Einstein
B. Guido Van Rossum
C. Guido Evan
D. None of these
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
A. Object
B. Logical
C. Real
D. Hypothetical
Q15: Which of the following can be considered a combination of data abstraction and
programming?
A. Class
B. Object
C. Inheritance
D. Interfaces
6. C 7. B 8. B 9. B 10. B
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
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.
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
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
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
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
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
13. Choose from the following that are Decision Tree nodes?
A. Decision Nodes
B. End Nodes
C. Chance Nodes
D. All of the mentioned
6. C 7. A 8. C 9. C 10. 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