PWP Important Semester Questions
PWP Important Semester Questions
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
4) 3D CAD Applications
7) Software Development
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
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
• 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.
• 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.
2) The variable are case sensitive, which means ‘soham’ and ‘SOHAM’ is different from one another.
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.
B) Immutable Data Types: The data types whose values cannot be changed. They include:
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)
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:
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, 30, 40] List = [10, 20, 30, 40, 50, 60, 70]
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.
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.
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.
2) Creating a Tuple with different data types: tuple = (10, “Soham”, 20.1)
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
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.
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.
List Tuple
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.
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}
A = {1, 2, 3}
A.update(B),
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.
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}
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}
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.
List Dictionary
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.
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.
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.
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.
• It is a collection of names.
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.
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.
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.
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().
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.
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().
index: This holds the index values for each element passed in data.
copy: It takes a Boolean value specifying whether or not to copy the data.
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
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 (__)
A) Default Constructor: The default constructor is simple constructor which does not accept any arguments.
Destructor: An destructor is automatically called / invoked when a object is destroyed. It is used for deallocating
memory.
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)
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal):
def speak(self):
print("Dog barks")
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
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)
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.
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: