0% found this document useful (0 votes)
105 views

PWP Important Semester Questions

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)
105 views

PWP Important Semester Questions

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/ 56

Programming With

Python
Important Questions For
Semester
Features Of Python
1) Easy to Learn And Use: Python is a simple, accessible, user-friendly language.

2) Cross Platform Language: Python can run on various operating system such as Windows, macOS, Linux.

3) Free And Open Source: Python is a free application which does not charge any cost to the user for using it.

4) Object Oriented Language: Python is a Object Oriented Programming Language (OOP) as it also supports
various OOP methods like Class, Polymorphism, Encapsulation, Abstraction, etc.

5) Interactive Mode: It is a feature of Python. It allows users to enter commands and get immediate response,
facilitating learning and experimentation.

6) Interpreted Language: Python is an interpreted language and hence executes the code line by line at a time.
This makes debugging and easy and thus suitable for beginners.

7) Database: Python offers several libraries and frameworks that make it easy to work with different database
systems.
Applications Of Python

1) Web Applications

2) Desktop GUI Applications

3) Image Processing Applications

4) 3D CAD Applications

5) Scientific and Numeric Applications

6) Audio and Video Based Applications

7) Software Development

8) Google, Facebook, Netflix, Spotify, NASA, etc.


Modes of Python

There are two ways to run Python Scripts:

A) Script Mode: This mode is where you write your code in a .py file and then run it with the python command.
This is the most common way that people use Python because it lets you write and save your code so that you
can use it again later.

B) Interactive Mode: It is used when an user wants to run one single line or one block of code. If one needs to
write a long piece of Python code or if the Python script spans multiple files, interactive mode is not
recommended.
Building Blocks Of Python

1) Character Set: It is a set of alphabets, letters, symbols and some special characters that are valid in python
programming language.

2) Variables: It is like a container that stores values that we can access or change.

3) Identifiers: It is the name given to a function, class, variable, module or other objects that is used in python
program.

4) Keywords: Keywords are reserved words which have special meaning and functions. The keywords are predefined
words with specific meaning in the python programs

5) Literals: A literal refers to the fixed value that directly appears in the program. Literals can be defined as data that is
given in a variable or constant.

6) Indentation: Most of the programming languages use curly brackets ({}) to define a block of code. Python uses
indentation.

7) Comments: They are non-executable text marked by '#' to provide explanations and enhance code readability.
Indentation

• Most of the programming languages like C, C++, Java, use braces {} to define a block of code. Python uses
indentation.

• A code block (block of a function, loop etc.) starts with indentation and ends with the first un-indented line.

• The amount of indentation is upto us, but it must be consistent throughout that block

Diagram of Indentations is as follows:

Block 1
Block 2
Block 3
Block 2, continuation
Block 1, continuation
Comments

• Comments: They are non-executable text marked by ‘#’ or ‘‘‘ to provide explanations and enhance code
readability

• There are Two Types of Comments in Python:

• A) Single Line Comment: Single line comments are created simply by beginning a line with the hash (#)
character, and they are automatically terminated at the end of the line.

• Example of Single Line Comment: #This is a Single Line comment.

• B) Multiline Comment: In some situations, multiline documentation is required for a program. If we have
comments that extend multiple lines then we can add a multiline comment using ‘‘‘ or “““ before the comment.

• Example of Multiline Comment:


‘‘‘ This is a Multiline Comment
Print is a statement’’’ or “““This is a Multiline Comment”””
Variable Declaration

Basic Rules to Declare Variables in Python Programming Language

1) A variable cannot begin with a number.

2) The variable are case sensitive, which means ‘soham’ and ‘SOHAM’ is different from one another.

3) No special characters are used except Underscore (_).

4) Variables can be of unlimited lengths.


Mutable and Immutable Data Structures
There are two types of Data Types:

A) Mutable Data Types: The data types whose values can be changed. They include:

 List: It is an ordered sequence of items. They are mutable and is very flexible.

 Set: Set is an unordered collection of unique items.

 Dictionary: It is an unordered collection of key-value pairs. Example: Emp={1:“Soham”, 2:“Sarthak”}

B) Immutable Data Types: The data types whose values cannot be changed. They include:

 Numbers: They contain Integers, Float, Complex Number, etc.

 String: It is a collection of text characters, special symbols or alphanumeric data. Example: (Soham, #)

 Tuple: It is an ordered sequence of items same as list. The only difference is that tuples are immutable.
Pyhton Data Types
Python data types define the kind of data a variable can hold. There are various Data Types in Python those are:

1) Numbers: Represents numeric data to perform mathematical operation. It contains Integers, Float. Complex
Number.

2) String: It is a collection of text characters, special symbols or alphanumeric data. Example: (Soham, #)

3) List: It is an ordered sequence of items. They are mutable and is very flexible. It can contain heterogeneous values
such as integers, float, etc. but commonly used to store collection of homogeneous objects.

4) Tuple: It is an ordered sequence of items same as list. The only difference is that tuples are immutable (cannot
change) Example: tup1=(10,20,30)

5) Set: Set is an unordered collection of unique items.

6) Dictionary: It is an unordered collection of key-value pairs. Example: Emp={1:“Soham”, 2:“Sarthak”}

7) Boolean: It represents Boolean values either True or False. (True / False)


Python Operators
Operators are special characters used to perform operations on variables and return a specific result. They also help in
evaluating expressions or conditional statements such as if…else and switch.

There are various types of Operators like

1) Arithmetic Operators #Used for Mathematical calculations.

2) Assignment Operators #Used to assign a value to a variable.

3) Relational / Comparison Operators #Used for comparing to variables.

4) Logical Operator #Used for Logical Operations.

5) Bitwise Operator #Used for manipulating data in bit level.

6) Identity Operator # Used to compare the memory address of two objects.

7) Membership Operator #Used to check the existence of a particular element.


 Arithmetic Operators: They are used in mathematical expressions in the same way that they are using
in algebra. They include Addition, Subtraction, Multiplication, Division, Modulus, Exponent, etc.

Operator Description Example


Addition (+) It is used to add two variables. A+B = 10
Subtraction (-) It is used to subtract two variables A-B = 0
Multiplication (*) It is used to multiply two variables A*B = 25
Division (/) It is used to divide two variables B/A = 1
Modulus (%) It is used to show the remainder B%A = 0
Exponent (**) It performs exponential calculation A**2 = 100
Floor Division (//) Division of operands where the solution is a B//A = 2
quotient left after removing decimal numbers
 Assignment Operators: They are used to assign a values to variables in Python.
Operator Description Example
== (Simple Assignment Assigns the values from right side to left side C = A + B, A + B = C
Operator) operands.
+= (Add and Assignment It adds right operand to the left operand and C += A, C = C + A
Operator) assigns the result to left operand.
-= (Subtract and Assignment It subtracts right operand to the left operand C -= A , C = C - A
Operator) and assigns the result to left operand.
*= (Multiply and Assignment It multiplies right operand to the left operand C *= A, C = C * A
Operator) and assigns the result to left operand.
/= (Division and Assignment It divides left operand with the right operand C /= A, C = C / A
Operator) and assigns the result to left operand.
%= (Modulo and Assignment It takes modulus using two operands and C %= A, C= C % A
Operator) assign the result to the left operand.
**= (Exponent and Performs exponential power calculation on C**A, C= C**A
Assignment Operator) operand and assigns value to the left operand
 Relational Operators / Comparison Operators: They are used to compare values of two variables
for various means. They also return true or false according to the condition. They are also called as
Relational Operators.

Operator Meaning Explanation Example Result

== Equal to operator. This operator indicates the 10==10 True


values are equal
!= Not Equal to operator. This operator indicates that 10!=10 False
the values are not equal.
< Greater Than operator. This operator is used for 10>10 False
checking greater value.
> Less Than operator. This operator is used for 10<10 False
checking smaller value.
>= Greater Than or Equal to This operator is used for 10>=10 True
operator checking greater or equal
value.
<= Less Than or Equal to This operator is used for 10<=10 True
operator checking smaller or equal
value.
 Logical Operators: They are used to compound conditions by combining two
or more relations. They include AND (&&), OR (||), NOT (!).

Operator Description Example


AND (Logical AND If both the operands are non- (A AND B) is False.
Operator) zero, then the condition
becomes true.
OR (Logical OR Operator) If any of the two operands are (A OR B) is True.
non-zero, than the condition
becomes true.
NOT (Logical NOT It is used to convert a true NOT (A and B) is True.
Operator) condition into false condition.
 Bitwise Operators: They are used to manipulate the data at the bit level.
Operator Description Example
& (Bitwise AND Operator) It performs Boolean AND operation (A & B ) is 2.
on each bit of its integer arguments.
| (Bitwise OR Operator) It performs Boolean OR operation (A | B) is 3.
on each bit of its integer arguments.
^ (Bitwise XOR Operator) Exclusive or means that either (A ^ B) is 1.
operand one is true or two, not both.
~ (Bitwise Not Operator) It is a unary operator and operates by (~B) is -4
reversing all bits in the operand.
<< (Bitwise Left Shift Operator) It moves all bits in its first operand to (A<<2) is 4
the left by the number of places
specified in the second operand.
>> (Bitwise Right Shift Operator) It moves all bits in its first operand to (A>>2) is 1
the right by the number of places
specified in the second operand.
 Identity Operator: It is used to compare the memory address of two objects.
Operator Description Example
Returns true, if the variables on either side of the A=3, B=3
is operator points to the same object and false print (A is B)
otherwise True
Return false, if the variable either side of the A=3, B=3
is not operator points to the same object and true print(A is not B)
otherwise False

 Membership Operator: It is used to find the existence of a particular element in the sequence.
Operator Description Example
in Returns true if values is found in list or in x=“Hello World”
sequence and false otherwise. print(‘H’ in x)
True
not in Returns true if values is not found in list or in x=“Hello World”
sequence and true otherwise. print(‘H’ not in x)
False
Conditional Statements / Decision Making Statements

Syntax:
1) If Statement: It executes a statement if a condition is true. if condition:
statement(s)

Syntax:
if condition:
2) If-else Statement: This condition takes care of a true as well as false condition. statement(s)
else:
statement(s)

Syntax:
if condition1:
3) Nested if Statements: When a programmer writes one if statement inside another if if condition2:
statement then it is called as Nested if Statements. statement1
else:
statement2
else:
statement(3)
Conditional Statements / Decision Making Statements

4) Multi-way-if-elif-else (Ladder) Statements: This is the same statement as else-if statement used in other
languages like Java.

The elif keyword is pythons way of saying "if the previous conditions were not true, then try this condition.

Test Expression
True Syntax:
Statement 1
1 if (condition1):
False
statements
True
elif (condition2):
Test Expression
Statement 2 statements
2
.
False .
Test Expression
True .
Statement 3
3 elif (condition n):
Body of else
statements
Statement just else:
below if-elseif statements
List

A list in python is a linear data structure. The elements in the list are stored in linear order one after another. A list is a
collection of items or elements. The index in lists always starts from 0 and ends with n-1, if the list contains n elements.

Defining List: In Python lists are written with square brackets ([]). A list is created by placing all the items (elements)
inside the square brackets ([]), separated by commas.

Creating a List:

1) Creating an Empty List: L1=[ ]

2) Creating a List with an integer element: L2 = [10, 20, 30]

3) Creating a List with string elements: L3 = [“Mango”, “Orange”, “Apple”]

4) Creating a List with mixed data: L4 = [1, “Two”, 3, “Four”]

5) Creating a List using inbuilt range() function: L5 = list(range(0,5))


Deleting And Updating Values in List

Deleting Values in List: Python provides many ways in Updating Values in List: List are mutable meaning their
which the elements in a list can be deleted. elements can be changed or updated unlike string or tuple.
Lets consider a list Lets consider a list

list = [10, 20, 30, 40] list = [10, 20, 30]

1) pop() Method: list.pop(2) 1) append() Method: list.append(40)

list = [10, 20, 40] list = [10, 20, 30, 40]

2) del Keyword: del (list[1]) 2) extend() Method: list.extend([60,70])

list = [10, 30, 40] List = [10, 20, 30, 40, 50, 60, 70]

3) remove() Method: list.remove(40) 3) insert() Method: list.insert(8, 80)

list= [10, 20, 30] List = [10, 20, 30, 40, 50, 60, 70, 80]
Built – In Functions and methods for List

Method Description
len(list) It returns the length of the list.
min(list) It returns the item that has the minimum value in a list.
max(list) It returns the item that has the maximum value in a list.
sum(list) Calculates the sum of all the elements of list.
list(seq) It converts a tuple into a list.

Methods of List Class


Method Syntax Description
append() list.append(item) The item can be numbers, strings, another list, dictionary, etc.
extend() list.extend() This extend() method selects a list and adds an element to the end
insert() list.insert(index, This index is positions where an element needs to be inserted
element) element this the element to be inserted in the list.
List Indexing
List Indexing: An individual item in the list can be accessed by using an index, which is an integer number that
indicates the relative position of the item in the list.

There are two types of Indexing


1) List Index: We can use the index operator [] to access an item in a list. Index starts from 0. So, a list having 5
elements will have index from 0 to 4.

Example: List1=[10,20,30,40,50]
List1=[0]
Output: 10

1) Negative Indexing: Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2
to the second last item, and so on.

Example: List2=[‘p’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’]


List2[-1]
Output: n
List Slicing

List Slicing: The Slicing feature used by python to obtain a specific subset or element of the data structure
using the colon (:) operator.

Syntax: list_name[start_index:end_index]

Example: L1=[10,20,30,40,50]
L1[0:3]
Output: L1[10,20]

Example: L2=[10,20,30,40,50]
L2[1:4]
Output: L2[20,30,40]
Tuple
Tuple: A Tuple is also a linear data structure. A python tuple is a sequence of data values called as items or elements.
A tuple is a collection of items which is ordered and unchangeable.

 Creating A Tuple: To create tuple all the elements or items are placed inside round brackets (()), separated by
commas and assigned to a variable.

1) Creating a Tuple with an Integer: tuple = (10, 20, 30)

2) Creating a Tuple with different data types: tuple = (10, “Soham”, 20.1)

3) Creating Tuple without Parenthesis: tuple = 10, 20, 30, 40

 Accessing Values in Tuple: Accessing item slash elements from the tuple is a method to get values stored in the
tuple from a particular location or index

1) index() method: tuple[1]

2) M:N Method: tuple[1:4]


Deleting And Updating Values in Tuple

Deleting Values in Tuple: Tuples are unchangeable so we


cannot remove items from it, but we can delete the tuple
completely.

Tuple = (10, 20, 30, 40) Updating Tuple: Tuples are immutable which
mean we cannot update or change the values of
1) del() Method: del tuple #Deletes the whole Tuple tuple elements.

2) Convert Tuple into List: tuple = (1, 2, 3, 4, 5)

list = list(tuple) #converts a tuple to list

B = tuple(list) #converts a list to tuple


Built – In Functions and methods for Tuple

Method Description
len(tuple) It returns the length of the tuple.
min(tuple) It returns the item that has the minimum value in a tuple.
max(tuple) It returns the item that has the maximum value in a tuple.
count() It returns the number of times a specified value occurs in a tuple.
tuple(seq) It converts a list into a tuple.

Methods of List Class


Method Description
count() Returns the number of times a specified value occurs
in a tuple.
index() Searches the tuple for a specified value and returns the
position of where it was found.
List Vs Tuple

List Tuple

Lists are mutable. Tuple are immutable.

It is better for performing operations such as It is better for accessing the element.
insertion and deletion.

List consumes more memory Tuple consumes less memory if compared to lists

List have several built in methods Tuple does not have many built in methods.

Unexpected changes and errors are more likely to In a tuple, it is hard for errors to occur.
occur.
Sets
Sets: The set data structure in python programming is used to implemented to support mathematical set operations.
Set is an unordered collection of unique items. Items stored in a set are not kept in any particular order.

 Creating Sets: There are 2 ways of creating sets in Python:

1) Creating Set with curly brackets({}): a = {1, 2, 3, 4, 5}

2) Creating Set with set(): s = set(a, b, c)

 Deleting Sets: There are three ways to delete sets in python programming. Lets consider a set = {1, 2, 3, 4, 5}

1) discard() Method: set.discard(2), Output: set = {1, 3, 4, 5} #Removes a specified element from the set.

2) remove() Method: set.remove(3), Output: set = {1, 2, 4, 5} #Removes a specified element from the set.

3) pop() Method: set.pop(), Output: set = {2, 3, 4, 5} #Random item gets deleted.

4) clear() Method: set.clear(), Output: set = {} #Removes all the items from the set.
Updating Values in Sets

Updating Sets: There are two ways to update a Set Lets consider a set: set = {1, 2, 3, 4}

1) Using add() Method: set.add(5),

 Output: set = {1, 2, 3, 4, 5} #Adds an element at the end of the set.

2) Using update() Method: Consider two Set:

A = {1, 2, 3}

B = {“A”, “B”, “C”}

A.update(B),

 Output: A = {1, 2, 3, “C”, “B”, “A”}


Built – In Functions and methods for Sets

Functions Description
len() Returns the length of the set.
min() Returns the smallest item in the set.
max() Returns the largest item in the set.
sum() Returns the sum of all elements in the set.

Methods of List Class


Method Description
discard(item) It removes the specified item from the set
remove(item) It Removes an element from the set.
pop() It Deletes an random element from the set.
add(item) It adds an item to the set.
update() It updates the set with the union of itself and others.
Dictionaries
Dictionary: A dictionary data structure is a mutable data type and is used to store key value pairs indexed by keys. A
dictionary is a associative data structure, means the elements / items are stored in an non-linear manner.

 Creating Dictionary: There are two ways of Creating Dictionary.

1) Creating Dictionary using {}: d1={1: “Soham”, 2: “Vedant”, 3:“Arnav”}

2) Creating Dictionary using dict(): Emp = dict({“ID”:20,“Name”:“Soham”,“Gender”:“Male”})

 Deleting Dictionary: There are multiple ways of Deleting a Dictionary.

1) pop() Method: Emp.pop(“Name”), Output: Emp ={“ID”:20,“Gender”:“Male”} //Removes the specified key value.

2) popitem() Method: Emp.popitem(), Output: Emp ={“ID”:20} // Removes the last item from the dictionary.

3) del keyword: del Emp(“ID”), Output: Emp ={}//Removes the specified key value if mentioned or entire dictionary.

4) clear() Method: Emp.clear(), Output: Emp ={} //Clears the entire dictionary.
Accessing And Updating Values in Dictionary

 Accessing Values in Dictionary: There are two ways of accessing values in a Dictionary. Lets consider a
Dictionary: dict = {“Name”: “Soham”, “Age”: 18}

1) Using []: dict1[“Name”], Output: “Soham”

2) Using get() Method: dict.get(“Name”), Output: “Soham”

 Updating Dictionary: The dictionary data type is flexible data type that can be modified according the
requirement. Lets consider a Dictionary: dict = {“Name”: “Soham”, “Age”: 18}

1) Using update() Method: dict.update({“Age”:25}), Output: dict = {“Name”:“Soham”, “Age”:25} #Here, we


updated age of “Soham” from 18 to 25.

2) Using update() Method: dict.update({“Gender”:“Male”}), Output: dict = {“Name”:“Soham”, “Age”:25,


“Gender”:“Male”} #Here, we added a new key “Gender” and value “Male” using the update() Method.
Built – In Functions and methods for Dictionary

Functions Description
len() Returns the length of the items in the dictionary.
all() Returns true if all the elements are true or empty.
any() Returns true if any one of the element is true or false it dictionary is empty.
sorted() Returns a new sorted list of keys in the dictionary.
type() Returns the type of the passed variable.

Methods of List Class


Method Description
clear() It removes all the elements of the dictionary.
keys() / values() It returns only the keys of the dictionary. / It returns only the values of the dictionary.
pop() It removes the element with the specified key.
popitem() It removes the last inserted key-value pair.
update() It updates the dictionary with the specified key value parts.
List Vs Dictionary

List Dictionary

It is an ordered collection of items. It is an unordered collection of items.

Uses Square Brackets (“[]”) Uses Curly Brackets (“{}”)

Accessed by index, starting from 0. Values are accessed using keys.

Allows duplicate items. Does not allow duplicate keys.


However, values can be duplicated.
Example: fruits = [“apple”, “banana”, “cherry”] Example: person = {“name”: “John”, “age”: 30}
Python Built – In Functions
The functions that are provided by the system itself are called as Python Built-In Functions.

Type Data Conversion Functions: There are two types of Python Data Conversion.

1) Python Implicit Data Type Conversion: Implicit conversion is when data type conversion takes place either
during compilation or during run time and is handled directly by Python.

2) Python Explicit Data Type Conversion: Explicit Conversion also known as type casting, where we force an
expression to be of a specific type.

Python In-Built Math's Functions


Functions Description
min() Returns the smallest value.
max() Returns the largest value.
sqrt() Returns the square root value.
factorial() Returns the factorial value.
Some Extra Built – In Functions in Python

Function Description
int(x [,base]) Converts x to an integer.
float(x) Converts x to a floating point number.
str(x) Converts x into a string
list(x) Converts x into a list.
tuple(x) Converts x into a tuple.
set(x) Converts x into a set.
dict(x) Converts x into a dictionary.
User – Defined Functions

User – Defined Function are those function that are declared by the user itself and not by the system.

Advantages of User Defined Functions

1) User Defined Functions help to decompose a large program into small segments which makes program easy to
understand, maintain and debug.

2) We can track a large python program easily when it is divided into multiple functions.

3) Reusability is the main advantage Python functions.

4) Functions in Python reduces the overall size of the program.


Function Arguments: Required, Keyword, Default, Variable Length Arguments

Function Argument: There are four types of arguments which can be called are Required, Keyword, Default, Variable
Length Arguments.

Required Argument: They are the arguments passed to a function in correct positional order.

Keywords Argument: Keyword arguments, or named arguments, are parameters passed to a Python function that
specify the argument name and value.

Default Argument: A default argument is an argument that assumes a default value if a value is not provided in the
function call for that argument.

Variable Length Argument: In many cases where we are required to process a function with more number of
arguments than we specified in the function definitions. These type or arguments are called as Variable Length
Argument.
Namespace
• A namespace is a system to have a unique name for each and every object in Python.

• An object might be a variable or a method.

• It is a collection of names.

• Namespaces avoids conflicts between classes, methods and objects.

• There are Three types of Namespace in Python:

Types of Namespaces:

1) Local Namespace: This namespace covers the local names inside a function.

2) Global Namespace: This namespace covers the name from various imported modules used in a project.

3) Built-In Namespace: This namespace covers the built-in functions and built-in exception names.
Scope of Variable
The scope of the variables determines the portion of the program where you can access a particular variable/identifier.
There are two types of Variable.

Local Variables: It can be accessed only inside the function in which they are declared.

Global Variable: It can be accessed throughout (outside) the entire program.


Local Variable Vs Global Variable
Local Variable Global Variable
Local variables are declared inside a function. Global variables are declared outside any function
Accessed only by the statements, inside a function in Accessed by any statement in the entire program.
which they are declared.
Local variables are alive only for a function. Global variables are alive till the end of the program.
A local variable is destroyed when the control of the A global variables is destroyed when the entire program
program exit out of the block in which local variable is is terminated.
declared.
Modules
Modules are primary the (.py) files which contain python programming code defining functions. Modules can be:

Writing Modules: Writing a module means simply creating a file which can contains python definitions and
statements.

Importing Modules: Import statement is used to imports a specific module by using its name. Import statement
creates a reference to that module

Aliasing Modules: It is possible to modify the names of modules and their functions within Python by using the
“as” keyword.

There are Two Main Types of Modules in Python:

A) Built In Modules: These modules by default exist in python.

B) User Defined Modules: These modules are customized and created by the users.
There are two types of Python Built-In Modules

1) Numeric and Mathematical Modules: This module provides numeric and math related functions and data types.

 Math and cmath Modules: Math module is used for trigonometric, logarithmic function for real numbers.
Whereas cmath module is used for working with mathematical functions for complex numbers.

 Decimal Modules: This module allows the user to use decimal numbers (floating point numbers)

 Fractional Module: This module allows the user to perform fractions on numbers.

 Random Module: This module allows the computer to pick an random number weather from the given
options or by his own.

 Statistics Module: This module provides access to different statistics functions.


2) Functional Programming Modules: This module provides functions and classes that support a functional
programming style and general operations on cables.

 Itertools Module: It provides us various ways to manipulate the sequence while we are traversing it. Itertools
is a Python module that provides functions for creating iterators for efficient looping. It contains chain(),
cycle().

 chain(): It is used for chaining multiple iterators together.


 cycle(): It is used for repeating the sequence of a single value indefinitely.

 Functools Module: Functools is another Python module that provides higher-order functions and operations
on callable objects.

 Operator Module: The operator module in Python provides a set of functions corresponding to the built-in
operators, like addition, subtraction, multiplication, etc.

 addition(): It allows you to perform addition between two operands.


 subtraction(): It allows you to perform subtraction between two operands.
 multiplication(): It allows you to perform multiplication between two operands.
Python Packages
A) Writing Python Packages: Creating a package is quite easy, since it makes use of the operating system’s inherent
hierarchical file structure.

B) Standard Packages: NumPy and SciPy are the standards packages used by Python programming.

 Math: Some of the most popular mathematical functions are defined in the math module. These include
trigonometric function, representation function, logarithmic functions and angle conversion functions.

 NumPy: NumPy stands for “Numerical Python”. It is the fundamental package for scientific computing with
Python. It provides a high – performance multidimensional array object and tools for working with these array.

 SciPy: It stands for Scientific Python. It is a library that uses NumPy for more mathematical functions. SciPy
uses NumPy arrays as the basic data structure and comes with modules for various commonly used tasks in
scientific programming.

 Matplotlib: It is a plotting library used for 2D graphics in python programming language. It contains Bar
Graph, Histogram, Scatter Plot.
C) Pandas: It is an open source Python Library providing high performance data manipulation and analysis tool
using its powerful data structure. It contains various package like series(), DataFrame(), Panel().

 data: It is the array that needs to be passed as to convert it into a series.

 index: This holds the index values for each element passed in data.

 dtype: It is the datatype of the data passed in the method.

 copy: It takes a Boolean value specifying whether or not to copy the data.

 Series: It is used for single dimensional array.

 Data Frame: It is used for 2 dimensional array.

 Panel: It is used for 3 dimensional array.


Object Oriented Programming in Python

Class: A class is a user defined blueprint or prototype from which objects are created. Classes provide a means of
bundling data and functionality together.

Object: An object is an instance of a class that has some attributes and behavior. Objects can be used to access the
attributes of the class.

Data Hiding: It is a software development technique specifically used in Object Oriented Programming (OOP) to
hide internal objects details (data members)

Data Encapsulation: We can restrict access of methods and variables in a class with the help of encapsulation. It will
prevent the from being modified by accident.

Data Abstraction: It refers to providing only essential information about the data to the outside world, hiding the
background details or implementation.
Access Modifiers

Access Modifiers for Methods and Variables are as follows:

Type Description
Public methods Accessible from anywhere i.e. inside the class in which they are defined, in the
sub class, in the same script file as well as outside the script file.

Private methods Accessible only in their own class, Starts with two underscores (__)

Public variables Accessible from anywhere.


Private variables Accessible only in their own class or by a method if defined. Starts with two
underscores (__)
Constructor & Destructor
Constructor: A constructor is a special member function i.e. is used to initialize the instance variable of a class. The
types of Constructor are as follows:

A) Default Constructor: The default constructor is simple constructor which does not accept any arguments.

B) Parameterized Constructor: The constructor with parameters is knowns as parameterized constructor.

Destructor: An destructor is automatically called / invoked when a object is destroyed. It is used for deallocating
memory.

Built-In Class Attributes

__dict__: It displays the dictionary in which the class’s namespace is stored

__name__: It displays the name of the class.

__doc__: It displays the documentation string of the class.


Method Overloading
Method Overloading: It is the ability to define a method with same name but with different number of parameters
or different types of parameters or both. With this ability one method can perform different tasks.

Example:

class Shape:
def area(self, a=None, b=None):
if a is not None and b is None:
calc = a * a
print("Area of square is:", calc)
elif a is not None and b is not None:
calc = a * b
print("Area of rectangle is:", calc)

shape = Shape() # Create an instance of the Shape class

shape.area(5) # Calculates area of square


shape.area(4, 6) # Calculates area of rectangle
Method Overriding
Method Overriding: Overriding is the ability of a class to change the implementation of a method provided by one
of its base class. Method Overriding is thus a strict part of the inheritance mechanism.

class Animal:
def speak(self):
print("Animal speaks")

class Dog(Animal):
def speak(self):
print("Dog barks")

animal = Animal() # Instantiate objects


dog = Dog()

animal.speak() # Output: Animal speaks


dog.speak() # Output: Dog barks
Inheritance X

Single Inheritance: A derived class with only one base class is called Single Inheritance. Y

X Y
Multiple Inheritance: A derived class with more than one base class is called Multiple
Inheritance.
Z

A
Hierarchical Inheritance: If one base class is inherited by more than one derived classes,
it is called Hierarchical Inheritance. Y Z
X

Multilevel Inheritance: When a class is derived from another derived class then it is
Y
called as Multilevel Inheritance.
Z
File Operations + Directory Operations

1) Reading File: It means reading a file.

2) Writing File: It means editing a file.

3) Opening File: It means opening a file.

4) Closing File: It means closing a file.

5) Renaming File: It means changing the name of the file.

6) Deleting File: It means deleting the file permanently.


Files and its Types:

File is a named location on disk to store related information. It is used to permanently store data in a non-volatile
memory. (hard disk)

There are Two Types of File Categories:

A) Text File: These are simple files that contains texts in human readable format. A text file is structured as
sequence of lines of text.

B) Binary File: These files have binary data (0s and 1s) which is understood by the computer. In python file
operations takes place as follows:

 Open a File.

 Read or Write a File. (perform operation)

 Close the File.


Different Modes of Operating File
Mode Description
r (Read Only) Opens a file for reading only.
w (Write Only) Opens a file for writing only.
rb (Read Binary) Opens a file for reading only in Binary Format.
wb (Write Binary) Opens a file for writing only in Binary Format.
r+ (Read + Write) Opens a file for both reading and writing.
w+ (Write + Read) Opens a file for both writing and reading.
rb+ (Read + Write Binary) Opens a file for both reading and writing in Binary Format.
wb+ (Write + Read Binary) Opens a file for both writing and reading in Binary Format
a (Appending) Opens a file for Appending.
ab (Appending Binary) Opens a file for Appending in Binary Format.
a+ (Appending + Reading) Opens a file for both Appending and Reading.
ab+ (Appending + Reading Binary) Opens a file for both appending and Reading in Binary Format
Exception Handling

In Python, exceptions can be handled using a try statement. A try block consisting of one or more statements is
used by programmer’s to partition code that might be affected by an exception.

A critical operation which can raise exception is placed inside the try clause and the code that handles the exception
is written in except clause.

Try Block: A set of statements that may cause error during runtime are to be written in the try block.

Except Block: It is written to display the exception details to the user when certain exception occurs in the
program. The except block is executed only when a certain type of exception occurs in the execution of statements
written in the try block.

Syntax:

You might also like