0% found this document useful (0 votes)
25 views39 pages

python final exam

The document outlines key features and applications of Python, emphasizing its ease of use, open-source nature, and support for various programming paradigms. It also covers important concepts such as indentation, logical operators, data structures (like lists, tuples, and dictionaries), and control flow statements (loops and conditionals). Additionally, it discusses the significance of Python libraries, GUI advantages, and data visualization.

Uploaded by

kensharma216
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)
25 views39 pages

python final exam

The document outlines key features and applications of Python, emphasizing its ease of use, open-source nature, and support for various programming paradigms. It also covers important concepts such as indentation, logical operators, data structures (like lists, tuples, and dictionaries), and control flow statements (loops and conditionals). Additionally, it discusses the significance of Python libraries, GUI advantages, and data visualization.

Uploaded by

kensharma216
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/ 39

2 MARKS

1. Features of Python
Easy to code: Python is a very developer friendly language which means that anyone can learn it.
Open source and free: It is an open-source programming language that is anyone can create and
contribute to it's development.
Object-oriented Approach: It recognizes the concept of class and object encapsulation.
Support for other language: Being coded in C, Python by default support the execution of code
written in other programming language such as Java, C and C++.
High-level language: This means no need to aware of the coding structure, architecture as well as
memory management while coding Python.
Support for GUI (Graphical User Interface): GUI has the ability to add flair to code and make the
results more visual.
Highly portable
Extensive array of library

2. Applications of Python.
• Developing web applications
• Desktop GUI applications
• Data analysis
• Machine learning applications
• Artificial intelligence applications
• Statistics
• Cloud computing
• Software development
• Scientific and Numeric
• Business applications

3. notes on Indentation in Python.


Indentation
Indentation refers to the spaces at the beginning of a code line.
Where in other programming languages the indentation in code is for readability only, the
indentation in Python is very important.
Python uses indentation to indicate a block of code.

4. Logical operators in Python.


Logical Expressions: These are kinds of expressions that result in either True or False. It basically
specifies one or more conditions.
For example, (10 == 9) is a condition if 10 is equal to 9. As we know it is not correct, so it will return
False. Studying logical expressions, we also come across some logical operators which can be seen in
logical expressions most often.
Here are some logical operators in Python:
Operator Syntax Functioning
AND P and Q It returns true if both P and Q are true otherwise returns false
OR P OR Q It returns true if at least one of P and Q is true
NOT NOT P It returns true if condition P is false
Example:
#Let’s have a look at an exemplar code :
P = (10 == 9)
Q = (7 > 5)
# Logical Expressions
R = P and Q
S = P or Q
T = not P
print(R)
print(S)
print(T)
Output
False
True
True

5. Syntax of creating Sets in Python.


Using the set() function
my_set = {value1, value2, value3, ...}
Example:
Set = {5,1,2.6,"python"}
print(Set)

6. Compare Lists and Tuples.


List
A list can contain a series of values.
List variables are declared by using brackets [ ].
A list is mutable, which means we can modify the list.
Example:
List = [2,4,5.5,"Hi"]
print("List[2] = ", List[2])
Output: List[2] = 5.5

Tuple
A tuple is a sequence of Python objects separated by commas.
Tuples are immutable, which means tuples once created cannot
be modified.
Tuples are defined using parentheses().
Example:
Tuple = (50,15,25.6,"Python")
print("Tuple[1] = ", Tuple[1])
Output: Tuple[1] = 15

7. Identifier
A Python identifier is a name used to identify a variable, function, class, module or other object. An
identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters,
underscores and digits (0 to 9).
Python does not allow punctuation characters such as @, $, and % within identifiers. Python is a
case sensitive programming language.

8. Scope of a Variable?
The scope is nothing but the visibility of variables
There are two primary scopes of variables in Python:
Local variable
Global variable
Nonlocal Variables

9. Lifetime of a Variable.
Lifetime is nothing but the duration which variable is exist.

10. Advantages of GUI in Python.


1. Easy to Use: GUIs make it easy for users to interact with the program, even if they are not familiar
with command-line interfaces.
2. Visual Appeal: GUIs can be designed to be visually appealing, making the program more engaging
and user-friendly.
3. Increased Productivity: GUIs can automate many tasks, reducing the time and effort required to
perform tasks.
4. Improved User Experience: GUIs provide a more intuitive and interactive way of interacting with
the program, making it easier for users to understand and use the program.

11. Nested lists?


A list within another list is referred to as a nested list in Python. We can also say that a list that has
other lists as its elements is a nested list.

12. Tuples in Python.


Tuple
A tuple is a sequence of Python objects separated by commas.
Tuples are immutable, which means tuples once created cannot
be modified.
Tuples are defined using parentheses().
Example:
Tuple = (50,15,25.6,"Python")
print("Tuple[1] = ", Tuple[1])
Output: Tuple[1] = 15

13. Purpose of Python Libraries.


In Python, libraries are used to refer to a collection of modules that are used repeatedly in various
programs without the need of writing them from scratch. Modules on the other hand refer to any
Python file saved with the .py extension. Modules often contain code such as functions, classes and
statements that can be imported and used within other programs.
14. String Slicing?
Access a range of characters in a string by using the slicing operator colon ” : “.
Example
greet = 'Hello'
# access character from 1st index to 3rd index
print(greet[1:4])
output : ell

15. Inheritance
Inheritance allows us to define a class that inherits all the methods and properties from another
class.
Parent class is the class being inherited from, also called base class.
Child class is the class that inherits from another class, also called derived class.
Syntax :
class BaseClass:
Body of base class
class DerivedClass(BaseClass):
Body of derived class

16. 2 Operations of List.


1. Definition operations
These operations allow us to define or create a list.
1.1) [ ]
Creates an empty list.
Output: y = []
2. Mutable operations
These operations allow us to work with lists, but altering or modifying their previous definition.
2.1) append
Adds a single item to the bottom of the list.
Example
x = [1, 2]
x.append('h')
print(x)
Output:
[1, 2, 'h']
2.2) extend
Adds another list to the end of a list.
Example
x = [1, 2]
x.extend([3, 4])
print(x)
Output:[1, 2, 3, 4]

17. Keyword Arguments


Keyword arguments (or named arguments) are values that, when passed into a function, are
identifiable by specific parameter names. A keyword argument is preceded by a parameter and the
assignment operator, = .
Example
def team(name, project):
print(name, "is working on an", project)
team(project = "Edpresso", name = 'FemCode')
Output:
FemCode is working on an Edpresso

18. Any 2 Operations of Files in Python


1. open ()
Python has a built-in function open() to open a file. Which accepts two arguments, file name and
access mode in which the file is accessed. The function returns a file object which can be used to
perform various operations like reading, writing, etc.
Note: if you want to create a file we have to use a open() Method. After it will create a new file.
Syntax:
Fileobject = open (file-name, access-mode)
file-name: It specifies the name of the file to be opened.
access-mode: There are following access modes for opening a file:
➢ "w"
Write - Opens a file for writing, creates the file if it does not exist.
➢ "r"
Read - Default value. Opens a file for reading, error if the file does not exist.
2. Reading Files in Python
After we open a file, we use the read() method to read its contents.
Example
# open a file
file1 = open("test.txt", "r")
# read the file
read_content = file1.read()
print(read_content)
Output
This is a test file.
Hello from the test file.

3. writing Files in Python


There are two things we need to remember while writing to a file.
If we try to open a file that doesn't exist, a new file is created.
If a file already exists, its content is erased, and new content is added to the file.
In order to write into a file in Python, we need to open it in write mode by passing "w" inside open()
as a second argument.
Suppose, we don't have a file named test2.txt. Let's see what happens if we write contents to the
test2.txt file.

19. Define Operators


To checks whether a value exists in a sequence (such as a list, tuple, or string) and returns a Boolean
value: True if the value is in the sequence, and False if it's not.
20. What are Lists
The list is a sequence data type which is used to store the collection of data. Tuples and String are
other types of sequence data types.
Or
A list is a collection of things, enclosed in square brakets “ [ ] “ and separated by commas.
Example of list in Python
Here we are creating Python List using [].
Var = ["Geeks", "for", "Geeks"]
print(Var)
Output: ["Geeks", "for", "Geeks"]

21. Define Recursion


“Recursion is the process of defining something in terms of itself”. we know that a function can call
other functions. It is even possible for the function to call itself. These types of construct are termed
as recursive functions.
Example
def factorial(x):
"""This is a recursive function
to find the factorial of an integer"""
if x == 1:
return 1
else:
return (x * factorial(x-1))
num = 3
print("The factorial of", num, "is", factorial(num))
Output
The factorial of 3 is 6

22. What are Files


It is a container of user information and stores data permanently. It is is located on the computer's
hard drive, which is non-volatile memory in nature.

23. Define Inheritance


Inheritance allows us to define a class that inherits all the methods and properties from another
class.
Parent class is the class being inherited from, also called base class.
Child class is the class that inherits from another class, also called derived class.
Syntax :
class BaseClass:
Body of base class
class DerivedClass(BaseClass):
Body of derived class

24. What are Dictionaries


Dictionaries are the most flexible built-in data type in python.
Dictionaries items are stored and fetched by using the key.
Dictionaries are used to store a huge amount of data.
To retrieve the value we must know the key.
In Python, dictionaries are defined within braces {}.
We use the key to retrieve the respective value. But not the other way around.

Syntax:
Key:value
Example:
Dict = {1:'Hi',2:7.5, 3:'Class'}
print(Dict)
Output: {1: ‘Hi’, 2: 7.5, 3: ‘Class’}

25. Data Visualization


Data visualization is a field in data analysis that deals with visual representation of data. It graphically
plots data and is an effective way to communicate inferences from data.
Using data visualization, we can get a visual summary of our data. With pictures, maps and graphs,
the human mind has an easier time processing and understanding any given data.

26. Define String.


A string is an ordered sequence of characters.
We can use single quotes or double quotes to represent strings. Multi-line strings can be
represented using triple quotes, ”’ or “””.
Strings are immutable which means once we declare a string we can’t update the already declared
string
Example:
String1 = "Welcome"
String2 ="To Python"
print(String1+String2)
Output: Welcome To Python
6 marks

1.Looping statements in Python with example.


Looping Statements
a) for loop
Using for loop, we can iterate any sequence or iterable variable. The sequence can be string, list,
dictionary, set, or tuple.
Syntax of for loop:
for element in sequence:
body of for loop
#Example to display first ten numbers using for loop
for i in range(1, 11):
print(i)
Output
1
2
3
4
5
6
7
8
9
10
b) While loop
In Python, The while loop statement repeatedly executes a code block while a particular
condition is true.
In a while-loop, every time the condition is checked at the beginning of the loop, and if it is true,
then the loop’s body gets executed.
When the condition became False, the controller comes out of the block.
Syntax of while-loop :
while condition:
body of while loop
#Example to calculate the sum of first ten numbers
num = 10
sum = 0
i=1
while i <= num:
sum = sum + i
i=i+1
print("Sum of first 10 number is:", sum)
output :
Sum of first 10 number is: 55
2.Conditional statements in Python.
Conditional statements

a) If statement in Python
In control statements, The if statement is the simplest form. It takes a condition and evaluates to
either True or False.
If the condition is True, then the True block of code will be executed, and if the condition is False,
then the block of code is skipped, and The controller moves to the next line
Syntax of the if statement
if condition:
statement 1
statement 2
statement n

Example
number = 6
if number > 5:
# Calculate square
print(number * number)
print('Next lines of code')
Output
36

b) If – else statement
The if-else statement checks the condition and executes the if block of code when the condition is
True, and if the condition is False, it will execute the else block of code.
Syntax of the if-else statement
if condition:
statement 1
else:
statement 2
If the condition is True, then statement 1 will be executed If the condition
is False, statement 2 will be executed. See the following flowchart for
more detail.

Example
password = input('Enter password ')
if password == "Divya":
print("Correct password")
else:
print("Incorrect Password")
Output 1:
Enter password Divya
Correct password
Output 2:
Enter password divya
Incorrect Password
c) if-elif-else
In Python, the if-elif-else condition statement has an elif blocks to
chain multiple conditions one after another. This is useful when you
need to check multiple conditions.
With the help of if-elif-else we can make a tricky decision. The elif
statement checks multiple conditions one by one and if the
condition fulfills, then executes that code.

Syntax of the if-elif-else statement:


if condition-1:
statement 1
elif condition-2:
stetement 2
elif condition-3:
stetement 3
...
else:
statement

Example
def user_check(choice):
if choice == 1:
print("Admin")
elif choice == 2:
print("Editor")
elif choice == 3:
print("Guest")
else:
print("Wrong entry")

user_check(1)
user_check(2)
user_check(3)
user_check(4)

Output:
Admin
Editor
Guest
Wrong entry

d) Nested if-else statement


In Python, the nested if-else statement is an if statement inside
another if-else statement. It is allowed in Python to put any
number of if statements in another if statement.
Indentation is the only way to differentiate the level of nesting. The
nested if-else is useful when we want to make a series of decisions.
Syntax of the nested-if-else:
if conditon_outer:
if condition_inner:
statement of inner if
else:
statement of inner else:
statement ot outer if
else:
Outer else
statement outside if block

Example
#Find a greater number between two numbers
num1 = int(input('Enter first number '))
num2 = int(input('Enter second number '))
if num1 >= num2:
if num1 == num2:
print(num1, 'and', num2, 'are equal')
else:
print(num1, 'is greater than', num2)
else:
print(num1, 'is smaller than', num2)
Output 1:
Enter first number 56
Enter second number 15
56 is greater than 15
Output 2:
Enter first number 29
Enter second number 78
29 is smaller than 78

3.Arithmetic Operators in Python.


Arithmetic Expressions:
An arithmetic expression is a combination of numeric values, operators, and sometimes parenthesis.
The result of this type of expression is also a numeric value. The operators used in these expressions
are arithmetic operators like addition, subtraction, etc. Here are some arithmetic operators inPython:
perators Syntax Functionig
+ x+y Addition
– x–y Subtraction
* x*y Multiplication
/ x/y Division
// x // y Quotient
% x%y Remainder
** x ** y Exponentiation

Example:
Let’s see an exemplar code of arithmetic expressions in Python :
# Arithmetic Expressions
x = 40
y = 12
add = x + y
sub = x - y
pro = x * y
div = x / y
print(add)
print(sub)
print(pro)
print(div)
Output
52
28
480
3.3333333333333335

4.Any 4 Methods of Lists.


1) append
Adds a single item to the bottom of the list.
Example
x = [1, 2]
x.append('h')
print(x)
Output:
[1, 2, 'h']

2) extend
Adds another list to the end of a list.
Example
x = [1, 2]
x.extend([3, 4])
print(x)
Output:[1, 2, 3, 4]
3)insert
Inserts a new element at a specific position in the list, this method receives the position as a first
argument, and the element to add as a second argument.
Example
x = [1, 2]
x.insert(0, 'y')
print(x)
Output:['y', 1, 2]
4) del
Deletes the element located in the specific index.
This method also has the possibility to remove a section of elements from the list, through the “:”
operator.
You only need to define a starting and end point [start:end], keep in mind that the end point will
not be considered.
These points can be ignored, whereby the 0 position will be the starting point, and the last position
in the list will be the end point.
Example 1
x = [1, 2, 3]
del x[1]
print(x)
Output: [1, 3]
5) remove
Removes the first match for the specified item.
Example
x = [1, 2, 'h', 3, 'h']
x.remove('h')
print(x)
Output:[1, 2, 3, 'h']
6) reverse
Reverses the order of the elements in the list, this places the final elements at the beginning, and the
initial elements at the end.
Example:
x = [1, 2, 'h', 3, 'h']
x.reverse()
print(x)
Output:['h', 3, 'h', 2, 1]
7) sort
By default, this method sorts the elements of the list from smallest to largest, this behavior can be
modified using the parameter
reverse = True.
Example 1
x = [3, 2, 1, 4]
x.sort()
print(x)
Output:[1, 2, 3, 4]
Example 2
y = ['R', 'C', 'Python', 'Java', 'R']
y.sort(reverse=True)
print(y)
Output:
['R', 'R', 'Python', 'Java', 'C']
It is important to know that when you apply the sort method, you must do it on lists that have
elements of the same data type, otherwise, you will face the TypeError exception.
One of the benefits of the sort method is the custom sorting. We just need to create a function
that sorting under some custom criteria, and then we can use it through the key argument.
custom sorting is slower than the default sort.
Custom sorting example:
def sorting_by_length(str):
return len(str)
x = ['Python', 'is', 'the', 'best']
x.sort(key=sorting_by_length)
print(x)
5.Recursive function with an example.
Recursive Functions
“Recursion is the process of defining something in terms of itself”. we know that a function can call
other functions. It is even possible for the function to call itself. These types of construct are termed
as recursive functions.
The following image shows the working of a recursive function called recurse.

Example
def factorial(x):
"""This is a recursive function to find the factorial of an integer"""
if x == 1:
return 1
else:
return (x * factorial(x-1))
num = 3
print("The factorial of", num, "is", factorial(num))
Output :
The factorial of 3 is 6
Note:
To create strings that span multiple lines, triple single quotes '''.
Triple double quotes """ are used to enclose the string.

6.Python program to demonstrate the Lists


Demonstrate the use of List.
list1[2]
print(list1)
list1[0] = 100
print("Modified List1:", list1)
length = len(list1)
print("Length of List1:", length)
maximum = max(list1)
minimum = min(list1)
print("Maximum in List1:", maximum)
print("Minimum in List1:", minimum)
list2 = [80, 90, 100]
concatenated_list = list1 + list2
print("Concatenated List:", concatenated_list)
repeated_list = list1 * 2
print("Repeated List:", repeated_list)
sliced_list = list1[1:2]
print("Sliced List:", sliced_list)
print(100 in list1)
print(1000 not in list1)
list1.append(50.5)
print("After Append:", list1)
popped_item = list1.pop(3)
print("Popped Item:", popped_item)
print("After Pop:", list1)
list1.insert(1, 100)
print("After Insert:", list1)
list2.extend([10, 20])
print("After Extend:", list2)
list2.sort()
print("After Sort:", list2)
list2.reverse()
print("After reverse", list2)

7.Explain the Operations of Files


The 6 common operations we usually perform on text files are the
following:
1. Open a text file
2. Read a text file
3. Write to a text file
4. Close a text file
1. open ()
Python has a built-in function open() to open a file. Which accepts two
arguments, file name and access mode in which the file is accessed.
The function returns a file object which can be used to perform various
operations like reading, writing, etc.
Note: if you want to create a file we have to use a open() Method. After
it will create a new file.
Syntax:
Fileobject = open (file-name, access-mode)
file-name: It specifies the name of the file to be opened.
access-mode: There are following access modes for opening a file:
In addition you can specify if the file should be handled as binary or text mode

Example:
fileptr = open("myfile.txt","r")
if fileptr:
print("file is opened successfully with read mode only")

Output:
file is opened successfully with read mode only

Example:
fileptr = open("myfile1.txt","x")
if fileptr:
Output:
new file was created successfully
2. Reading Files in Python
After we open a file, we use the read() method to read its contents.
Example
# open a file
file1 = open("test.txt", "r")
# read the file
read_content = file1.read()
print(read_content)
Output
This is a test file.
Hello from the test file.
3. writing Files in Python
There are two things we need to remember while writing to a file.
If we try to open a file that doesn't exist, a new file is created.
If a file already exists, its content is erased, and new content is
added to the file.
In order to write into a file in Python, we need to open it in write mode by passing "w" inside open()
as a second argument.
Suppose, we don't have a file named test2.txt. Let's see what happens if we write contents to the
test2.txt file.
Example
with open(test2.txt', 'w') as file2:
# write contents to the test2.txt file
file2.write('Programming is Fun.')
file2.write('Programiz for beginners')
Here, a new test2.txt file is created and this file will have contents
specified inside the write() method.
Output:
Programming is fun
Programiz for Biginners

4. closing Files in Python


When we are done with performing operations on the file, we need to
properly close the file.
Closing a file will free up the resources that were tied with the file. It is
done using the close() method in Python. For example,
Example
# open a file
file1 = open("test.txt", "r")
# read the file
read_content = file1.read()
print(read_content)
# close the file
file1.close()
Output
This is a test file.
Hello from the test file.

8.. Multilevel Inheritance with an example program.


Multilevel inheritance
In multilevel inheritance, a class inherits from a child class or derived class. Suppose three classes A,
B, C. A is the superclass, B is the child class of A, C is the child class of B. In other words, we can say a
chain of classes is called multilevel inheritance.

Syntax
class BaseClass1:
Body of base class
class Derived_Class1(BaseClass1):
Body of derived class
class Derived_class2(Derived_Class1):
Body of derived class
Example
# Base class
class Vehicle:
def Vehicle_info(self):
print('Inside Vehicle class')
# Child class
class Car(Vehicle):
def car_info(self):
print('Inside Car class')
# Child class
class SportsCar(Car):
def sports_car_info(self):
print('Inside SportsCar class')
# Create object of SportsCar
s_car = SportsCar()
# access Vehicle's and Car info using SportsCar object
s_car.Vehicle_info()
s_car.car_info()
s_car.sports_car_info()
Output
Inside Vehicle class
Inside Car class
Inside SportsCar class

9. Types of Inheritance
Types Of Inheritance
In Python, based upon the number of child and parent classes involved,
there are five types of inheritance.
1. Single inheritance
2. Multiple Inheritance
3. Multilevel inheritance
4. Hierarchical Inheritance
5. Hybrid Inheritance

1. Single inheritance
In single inheritance, a child class inherits from a single-parent class. Here is one child class and one
parent class.

The general syntax is


class BaseClass:
Body of base class
class DerivedClass(BaseClass):
Body of derived class
Example
Let’s create one parent class called ClassOne and one child class called ClassTwo to implement single
inheritance.
# Base class
class Vehicle:
def Vehicle_info(self):
print('Inside Vehicle class')
# Child class
class Car(Vehicle):
def car_info(self):
print('Inside Car class')
# Create object of Car
car = Car()
# access Vehicle's info using car object
car.Vehicle_info()
car.car_info()
Output
Inside Vehicle class
Inside Car class
2. Multiple Inheritance
In multiple inheritance, one child class can inherit from multiple parent classes. So here is one child
class and multiple parent classes.

The general syntax is


class BaseClass1:
Body of base class
class BaseClass2:
Body of Base class
class Derived_class(Baseclass1, Baseclass2):
Body of derived class
Example
# Parent class 1
class Person:
def person_info(self, name, age):
print('Inside Person class')
print('Name:', name, 'Age:', age)
# Parent class 2
class Company:
def company_info(self, company_name, location):
print('Inside Company class')
print('Name:', company_name, 'location:', location)
# Child class
class Employee(Person, Company):
def Employee_info(self, salary, skill):
print('Inside Employee class')
print('Salary:', salary, 'Skill:', skill)
# Create object of Employee
emp = Employee()
# access data
emp.person_info('Jessa', 28)
emp.company_info('Google', 'Atlanta')
emp.Employee_info(12000, 'Machine Learning')
Output
Inside Person class
Name: Jessa Age: 28
Inside Company class
Name: Google location: Atlanta
Inside Employee class
Salary: 12000 Skill: Machine Learning
3. Multilevel inheritance
In multilevel inheritance, a class inherits from a child class or derived class. Suppose three classes A,
B, C. A is the superclass, B is the child class of A, C is the child class of B. In other words, we can say a
chain of classes is called multilevel inheritance.

Syntax
class BaseClass1:
Body of base class
class Derived_Class1(BaseClass1):
Body of derived class
class Derived_class2(Derived_Class1):
Body of derived class
Example
# Base class
class Vehicle:
def Vehicle_info(self):
print('Inside Vehicle class')
# Child class
class Car(Vehicle):
def car_info(self):
print('Inside Car class')
# Child class
class SportsCar(Car):
def sports_car_info(self):
print('Inside SportsCar class')
# Create object of SportsCar
s_car = SportsCar()
# access Vehicle's and Car info using SportsCar object
s_car.Vehicle_info()
s_car.car_info()
s_car.sports_car_info()
Output
Inside Vehicle class
Inside Car class
Inside SportsCar class
4. Hierarchical Inheritance
In Hierarchical inheritance, more than one child class is derived from a single parent class. In other
words, we can say one parent class and multiple child classes.

Syntax
class BaseClass1:
Body of base class
class Derived_Class1(BaseClass1):
Body of derived class
class Derived_class2(BaseClass1):
Body of derived class
class Derived_class3(BaseClass1):
Body of derived class
Example
class Vehicle:
def info(self):
print("This is Vehicle")
class Car(Vehicle):
def car_info(self, name):
print("Car name is:", name)
class Truck(Vehicle):
def truck_info(self, name):
print("Truck name is:", name)
obj1 = Car()
obj1.info()
obj1.car_info('BMW')
obj2 = Truck()
obj2.info()
obj2.truck_info('Ford')
Output
This is Vehicle
Car name is: BMW
This is Vehicle
Truck name is: Ford
5. Hybrid Inheritance
When inheritance is consists of multiple types or a combination of different inheritance is called
hybrid inheritance.

Syntax
class BaseClass1:
Body of base class
class Derived_Class1(BaseClass1):
Body of derived class
class Derived_class2(BaseClass2):
Body of derived class
class Derived_class3(Derived_Class1, Derived_class2):
Body of derived class
Example
class Vehicle:
def vehicle_info(self):
print("Inside Vehicle class")
class Car(Vehicle):
def car_info(self):
print("Inside Car class")
class Truck(Vehicle):
def truck_info(self):
print("Inside Truck class")
# Sports Car can inherits properties of Vehicle and Car
class SportsCar(Car, Vehicle):
def sports_car_info(self):
print("Inside Sports Car class")
# create object
s_car = SportsCar()
s_car.vehicle_info()
s_car.car_info()
s_car.sports_car_info()
Output
Inside Vehicle class
Inside Car class
Inside Sports Car class

10.Program to draw Line Chart using Matplotlib.


# Line chart
import matplotlib.pyplot as plt
x=[1,2,3,4,5]
y=[10,20,30,40,50]
plt.plot(x, y, marker='o', linestyle='-', color='b')
plt.title('Line Chart Example')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.legend()
plt.grid(True)
plt.show()

11.Operations of Dictionaries

12.User-defined functions with an example.


8 marks
1) String Concatenation

2) String Slicing

3) Logical Operators
Logical Expressions: These are kinds of expressions that result in either True or False. It basically
specifies one or more conditions.
For example, (10 == 9) is a condition if 10 is equal to 9. As we know it is not correct, so it will return
False. Studying logical expressions, we also come across some logical operators which can be seen in
logical expressions most often.
Here are some logical operators in Python:
Operator Syntax Functioning
AND P and Q It returns true if both P and Q are true otherwise returns false
OR P OR Q It returns true if at least one of P and Q is true
NOT NOT P It returns true if condition P is false

4) Data Types in Python


Data Types
Data types are the classification or categorization of data items. It represents the kind of value that
tells what operations can be performed on a particular data. Since everything is an object in Python
programming, data types are actually classes and variables are instances (object) of these classes.
The following are the standard or built-in data types in Python:
• Numeric
• Sequence Type
• Boolean
• Set
• Dictionary
• Binary Types( memoryview, bytearray, bytes)
Numeric Data Type in Python
The numeric data type in Python represents the data that has a numeric value. A numeric value can
be an integer, a floating number, or even a complex number.
These values are defined as Python int, Python float, and Python complex classes in Python.
Integers – This value is represented by int class. It contains positive or negative whole numbers
(without fractions or decimals). In Python, there is no limit to how long an integer value can be.
Float – This value is represented by the float class. It is a real number with a floating-point
representation. It is specified by a decimal point. Optionally, the character e or E followed by a
positive or negative integer may be appended to specify scientific notation.
Complex Numbers – Complex number is represented by a complex class. It is specified as (real part)
+ (imaginary part)j. For example – 2+3j
Note – type() function is used to determine the type of data type.
Python3
# Python program to # demonstrate numeric value
a=5
print("Type of a: ", type(a))
b = 5.0
print("\nType of b: ", type(b))
c = 2 + 4j
print("\nType of c: ", type(c))
Output:
Type of a: <class 'int'>
Type of b: <class 'float'>
Type of c: <class 'complex'>

Sequence Data Type in Python


The sequence Data Type in Python is the ordered collection of similar or different data types.
Sequences allow storing of multiple values in an organized and efficient fashion.
There are several sequence types in Python –
Python String
Python List
Python Tuple

String Data Type


Strings in Python are arrays of bytes representing Unicode characters. A string is a collection of one
or more characters put in a single quote, double-quote, or triple quote. In python there is no
character data type, a character is a string of length one. It is represented by str class.
Python3
# Python Program for
# Creation of String
# Creating a String
# with single Quotes
String1 = 'Welcome to the Geeks World'
print("String with the use of Single Quotes: ")
print(String1)

# Creating a String
# with double Quotes
String1 = "I'm a Geek"
print("\nString with the use of Double Quotes: ")
print(String1)
print(type(String1))

# Creating a String
# with triple Quotes
String1 = '''I'm a Geek and I live in a world of "Geeks"'''
print("\nString with the use of Triple Quotes: ")
print(String1)
print(type(String1))

# Creating String with triple


# Quotes allows multiple lines
String1 = '''Geeks
For
Life'''
print("\nCreating a multiline String: ")
print(String1)
Output:
String with the use of Single Quotes:
Welcome to the Geeks World

String with the use of Double Quotes:


I'm a Geek
<class 'str'>

String with the use of Triple Quotes:


I'm a Geek and I live in a world of "Geeks"
<class 'str'>
List Data Type
Lists are just like arrays, declared in other languages which is an ordered collection of data. It is very
flexible as the items in a list do not need to be of the same type.
Python3
# Creating a List
List = []
print("Initial blank List: ")
print(List)
Output:
Initial blank List:
[]

List with the use of String:


['GeeksForGeeks']

Tuple Data Type


Just like a list, a tuple is also an ordered collection of Python objects. The only difference between a
tuple and a list is that tuples are immutable i.e. tuples cannot be modified after it is created. It is
represented by a tuple class.
Python3
# Creating an empty tuple
Tuple1 = ()
print("Initial empty Tuple: ")
print(Tuple1)

Output:
Initial empty Tuple:
()

Boolean Data Type in Python


Data type with one of the two built-in values, True or False. Boolean objects that are equal to True
are truthy (true), and those equal to False are falsy (false). But non-Boolean objects can be evaluated
in a Boolean context as well and determined to be true or false. It is denoted by the class bool.
Note – True and False with capital ‘T’ and ‘F’ are valid booleans otherwise python will throw an error.
Python3
# Python program to
# demonstrate boolean type
print(type(True))
print(type(False))
print(type(true))
Output:
<class 'bool'>
<class 'bool'>
Traceback (most recent call last):
File "/home/7e8862763fb66153d70824099d4f5fb7.py", line 8, in
print(type(true))
NameError: name 'true' is not defined

Set Data Type in Python


In Python, a Set is an unordered collection of data types that is iterable, mutable and has no
duplicate elements. The order of elements in a set is undefined though it may consist of various
elements.
Python3
# Python program to demonstrate
# Creation of Set in Python
# Creating a Set
set1 = set()
print("Initial blank Set: ")
print(set1)
Output:
Initial blank Set:
set()

Dictionary Data Type in Python


A dictionary in Python is an unordered collection of data values, used to store data values like a map,
unlike other Data Types that hold only a single value as an element, a Dictionary holds a key: value
pair. Key-value is provided in the dictionary to make it more optimized. Each key-value pair in a
Dictionary is separated by a colon : , whereas each key is separated by a ‘comma’.
Python3
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
Output:
Empty Dictionary:
{}

Console input and output


Console input
Syntax: input([prompt])
Prompt is the string we like to display on the screen prior to talking the input
The input() takes exactly what is typed from the keyboard, converts into string
and assigns it to the variable on left-hand side of the assignment operator(=).
Console output
print()
Syntax:print(values(s),sep=‘ ‘,end=‘\n’, file=file, flush=flush)
Parameter
value(s):any values(s)
Sep=‘separator’: Specify how to separate the object
End:default”\n”
File:file write method
Flush:boolean
5) Python program to implement Classes and Objects.
Class
The class can be defined as a collection of objects. It is a logical
entity that has some specific attributes and methods.
To define a class in Python, you can use the class keyword,
followed by the class name and a colon.
Inside the class, an “ _ _init_ _ “ method has to be defined with
def.
This is the initializer that you can later use to instantiate objects.
It's similar to a constructor in Java.
For example: if you have an employee class, then it should contain an attribute and method, i.e. an
email id, name, age, salary, etc.
Example
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def __str__(self):
return f"{self.name}({self.age})"
p1 = Person("John", 36)
print(p1)
output:
John(36)
The general syntax is
class ClassName:
<statement-1>
.
.
<statement-N>
Creating a class
The general syntax is
class classname:
def __init__(self):
pass

Objects
The object is an entity that has state and behaviour. It may be any real-world object like the
mouse, keyboard, chair, table, pen, etc.
Everything in Python is an object, and almost everything has attributes and methods. All functions
have a built-in attribute __doc__, which returns the docstring defined in the function
source code.
When we define a class, it needs to create an object to allocate the
memory.
Creating an object
The general syntax is
Objectname=classname();
Example 1:
class car:
def __init__(self,modelname, year):
self.modelname = modelname
self.year = year
def display(self):
print(self.modelname,self.year)
c1 = car("Toyota", 2016)
c1.display()
Output:
Toyota 2016

EXAMPLE PROGRAM OF CLASS AND OBJECT:


# Define a class called "Car"
class Car:
# Class attributes
wheels = 4
doors = 4

# Constructor (special method)


def __init__(self, color, model, year):
# Instance attributes
self.color = color
self.model = model
self.year = year
self.mileage = 0

# Method to drive the car


def drive(self, miles):
self.mileage += miles
print(f"You drove {miles} miles. Total mileage: {self.mileage} miles.")

# Method to describe the car


def describe(self):
print(f"This car is a {self.year} {self.color} {self.model} with {self.wheels} wheels and {self.doors}
doors.")

# Create an object (instance) of the Car class


my_car = Car("Red", "Toyota", 2020)

# Access and modify instance attributes


print(my_car.color) # Output: Red
my_car.color = "Blue"
print(my_car.color) # Output: Blue

# Call methods on the object


my_car.drive(100) # Output: You drove 100 miles. Total mileage: 100 miles.
my_car.describe() # Output: This car is a 2020 Blue Toyota with 4 wheels and 4 doors.
# Create another object (instance) of the Car class
your_car = Car("Silver", "Honda", 2015)

# Access and modify instance attributes


print(your_car.color) # Output: Silver
your_car.color = "Black"
print(your_car.color) # Output: Black

# Call methods on the object


your_car.drive(50) # Output: You drove 50 miles. Total mileage: 50 miles.
your_car.describe() # Output: This car is a 2015 Black Honda with 4 wheels and 4 doors.

6) Explain any 3 Operations of Dictionaries.

7) Program to demonstrate Exceptions handling.


print("Select the type of exception to demonstrate.")
print("1. ZeroDivisionError")
print("2. IndexError")
print("3. TypeError")
print("4. Generic Exception and else block demo")

while True:
choice = input("Enter choice (1/2/3/4): ")
try:
if choice == '1':
numerator = 10
denominator = 0
result = numerator / denominator
print(result)
elif choice == '2':
even_numbers = [2, 4, 6, 8]
print(even_numbers[5]) # May raise IndexError
elif choice == '3':
number = 'one'
print(number + 1) # raise TypeError
elif choice == '4':
# print(foo) # raise a NameError
num1 = int(input("Enter a character value to generate an exception. Enter an
integer to demonstrate the else block execution:"))
print(num1)
except IndexError:
print("Index Out of Bound.")
except ZeroDivisionError:
print("Cannot divide a number by Zero.")
except TypeError:
print("Can't concatenate a string and an int.")
except Exception as e:
print('Sorry, an error occurred somewhere!')
print('Exception that was generated is - ')
print(e)
else:
print("No exception occurred.")
finally:
print("This is the finally block.")

8) Default Arguments . Give example.


In Python, we can provide default values to function arguments. We use the ” = “ Assignment
operator to provide default values. In other words, Default values indicate that the function
argument will take that value if no argument value is passed during the function call.
The default value is assigned by using the assignment(=) operator of the form
”keywordname=value“.
Example
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function() #It will take default values i.e Norway
my_function("Brazil")
Output
I am from Sweden
I am from India
I am from Norway
I am from Brazil

9) Any 4 String Functions………(refer 16th q)

10) Program to Read and Write Data into a File.


f = open("C:\\Users\\Gowth\\Desktop\\pro.txt", "r")
print(f.read())
f.close()

f = open("C:\\Users\\Gowth\\Desktop\\python.txt", "w")
f.write("i love python")
f.close()

11) Constructors in Python with an example.


A constructor is a special type of method (function) which is used to initialize the instance members
of the class.
In C++ or Java, the constructor has the same name as its class, but it treats constructor differently
in Python.
It is used to create an object.
Constructors can be of two types.
1. Parameterized Constructor
2. Non-parameterized Constructor

Creating the constructor in python


In Python, the method the __init__() simulates the constructor of the class. This method is called
when the class is instantiated. It accepts the self-keyword as a first argument which allows accessing
the attributes or method of the class.
We can pass any number of arguments at the time of creating the class object, depending upon the
__init__() definition. It is mostly used to initialize the class attributes. Every class must have a
constructor, even if it simply relies on the default constructor.
Example
class Employee:
def __init__(self, name, id):
self.id = id
self.name = name
def display(self):
print("ID: %d \nName: %s" % (self.id, self.name))
emp1 = Employee("John", 101)
emp2 = Employee("David", 102)
#accessing display() method to print employee 1 information
emp1.display()
#accessing display() method to print employee 2 information
emp2.display()
Output:
ID: 101
Name: John
ID: 102
Name: David

1. Non-Parameterized Constructor
The non-parameterized constructor uses when we do not want to manipulate the value or the
constructor that has only self as an argument. Consider the following example.
Example
class Student:
# Constructor - non parameterized
def __init__(self):
print("This is non parametrized constructor")
def show(self,name):
print("Hello",name)
student = Student()
student.show("John")
2. Parameterized Constructor
The parameterized constructor has multiple parameters along with the self. Consider the following
Example.
class Student:
# Constructor - parameterized
def __init__(self, name):
print("This is parametrized constructor")
self.name = name
def show(self):
print("Hello",self.name)
student = Student("John")
student.show()
Output:
This is parametrized constructor
Hello John

12) How to Create and Store Strings

13) Console Input / Output statements


Console input
Syntax: input([prompt])
Prompt is the string we like to display on the screen prior to talking the input The input() takes
exactly what is typed from the keyboard, converts into string and assigns it to the variable on left-
hand side of the assignment operator(=).
Console output
print()
Syntax:print(values(s),sep=‘ ‘,end=‘\n’, file=file, flush=flush)
Parameter
value(s):any values(s)
Sep=‘separator’: Specify how to separate the object
End:default”\n”
File:file write method
Flush:boolean

14) How to Class created in Python? Explain with an example program.


The class can be defined as a collection of objects. It is a logical entity that has some specific
attributes and methods.
To define a class in Python, you can use the class keyword, followed by the class name and a colon.
Inside the class, an “ _ _init_ _ “ method has to be defined with def.
This is the initializer that you can later use to instantiate objects.
It's similar to a constructor in Java.
“ _ _init_ _ “ must always be present! It takes one argument: self, which refers to the object itself.
The self is used to represent the instance of the class. With this keyword, you can access the
attributes and methods of the class in python. It binds the attributes with the given arguments.
The reason why we use self is that Python does not use the '@' syntax to refer to instance
attributes.
For example: if you have an employee class, then it should contain an attribute and method, i.e. an
email id, name, age, salary, etc.
Note:
1. The _ _init_ _() Function
The examples above are classes and objects in their simplest form, and are not really useful in real
life applications.
To understand the meaning of classes we have to understand the built-in _ _init_ _() function.
All classes have a function called _ _init_ _(), which is always executed when the class is being
initiated.
Use the _ _init_ _() function to assign values to object properties, or other operations that are
necessary to do when the object is being created:
2. The __str__() Function
The __str__() function controls what should be returned when the class object is represented as a
string.
If the __str__() function is not set, the string representation of the object is returned:
Example
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def __str__(self):
return f"{self.name}({self.age})"
p1 = Person("John", 36)
print(p1)
output:
John(36)

The general syntax is


class ClassName:
<statement-1>
.
.
<statement-N>
Creating a class
The general syntax is
class classname:
def __init__(self):
pass
To define a class in Python, you can use the class keyword, followed by the class name and a colon.
Inside the class, an “ _ _init_ _ “ method has to be defined with def.
This is the initializer that you can later use to instantiate objects.
It's similar to a constructor in Java.
“ _ _init_ _ “ must always be present! It takes one argument: self, which refers to the object itself.
The self is used to represent the instance of the class. With this keyword, you can access the
attributes and methods of the class in python. It binds the attributes with the given arguments.
Inside the method, the pass keyword is used as of now, because Python expects you to type
something there.
Example 1:
class Dog:
def __init__(self):
pass
Adding attributes to a class
Adding attributes to a class is
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
You can see that the function now takes two arguments after self: name and age. These then get
assigned to self.name and self.age respectively
Example 2:
class Parrot:
# class attribute
name = ""
age = 0
# create parrot1 object
parrot1 = Parrot()
parrot1.name = "Ram"
parrot1.age = 10
# create another object parrot2
parrot2 = Parrot()
parrot2.name = "Manju"
parrot2.age = 15
# access attributes
print(f"{parrot1.name} is {parrot1.age} years old")
print(f"{parrot2.name} is {parrot2.age} years old")
Output
Ram is 10 years old
Manju is 15 years old
Explanation:
In the above example, we created a class with the name Parrot with two attributes: name and age.
Then, we create instances of the Parrot class. Here, parrot1 and parrot2 are references (value) to
our new objects.
We then accessed and assigned different values to the instance attributes using the objects name
and the dot (.) notation.

15) Constructor in Python.example.(refer 8 marks 11 q)

16) String Functions .


1. upper()
The upper() function returns a string with all characters converted to uppercase.
2. lower()
The lower() function returns a string with all characters converted to lowercase.
3. capitalize()
The capitalize() function returns a string with the first character capitalized and the rest of the
characters in lowercase.
4. count()
The count() function returns the number of occurrences of a specified substring within a string.
5. isdigit()
The isdigit() function returns True if all characters in a string are digits, and False otherwise.
6. isupper()
The isupper() function returns True if all characters in a string are uppercase, and False otherwise.
7. islower()
The islower() function returns True if all characters in a string are lowercase, and False otherwise.
8. replace()
The replace() function returns a string with all occurrences of a specified substring replaced with
another substring.
9. title()
The title() function returns a string with the first character of each word capitalized.
10. split()
The split() function splits a string into a list of substrings, separated by a specified separator.

EXAMPLE PROGRAM:
str1 = "new horizon"

print("\n 1.upper() function: ")


str2 = str1.upper()
print(str2)

print("\n 2.lower() function: ")


str3 = str1.lower()
print(str3)

print("\n 3.capitalize() function: ")


str4 = str1.capitalize()
print(str4)

print("\n 4.count() function: ")


count1 = str1.count('e')
print(count1)

print("\n 5.IsDigit() function: ")


ans1 = str1.isdigit()
print(ans1)

print("\n 6.Isupper() function: ")


ans2 = str1.isupper()
print(ans2)

print("\n 7.Islower() function: ")


ans3 = str1.upper()
print(ans3)

print("\n 8.Replace() function: ")


str5 = str1.replace('o', 'i')
print(str5)

print("\n 9.Title() function: ")


str6 = str1.title()
print(str6)

print("\n 10.Split() function: ")


str7 = str1.split()
print(str7)

17) User-defined Functions?Program to demonstrate User-defined functions.

18)Encapsulation
Definition: It describes the concept of bundling data and methods within a single unit.
Example: when you create a class, it means you are implementing encapsulation. A class is an
example of encapsulation as it binds all the data members (instance variables) and methods into a
single unit.

19) Polymorphism
Polymorphism
Polymorphism refers to having multiple forms. Polymorphism is a programming term that refers to
the use of the same function name, but with different signatures, for multiple types.
Example 1
integer data types, “+” operator is used to perform arithmetic addition
operation.
num1 = 1
num2 = 2
print(num1+num2)
output: 3
Example 2
Similarly, for string data types,” + “ operator is used to perform
concatenation.
str1 = "Python"
str2 = "Programming"
print(str1+" "+str2)
output: Python Programming

20)For loop with an example. (refer 6marks 1 q)


st

You might also like