python final exam
python final exam
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
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.
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
Syntax:
Key:value
Example:
Dict = {1:'Hi',2:7.5, 3:'Class'}
print(Dict)
Output: {1: ‘Hi’, 2: 7.5, 3: ‘Class’}
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.
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
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
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
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.
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
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.
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
11.Operations of Dictionaries
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
# 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))
Output:
Initial empty Tuple:
()
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
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.")
f = open("C:\\Users\\Gowth\\Desktop\\python.txt", "w")
f.write("i love python")
f.close()
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
def __str__(self):
return f"{self.name}({self.age})"
p1 = Person("John", 36)
print(p1)
output:
John(36)
EXAMPLE PROGRAM:
str1 = "new horizon"
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