Exam Score Booster
Exam Score Booster
Algorithm:
1. Start
2. Initialize two variables, num1 and num2, to store the entered numbers.
3. Read the first number num1 from the user.
4. Read the second number num2 from the user.
5. Add num1 and num2 to calculate the sum and store it in a variable called sum.
6. Display the value of sum as the result of the addition.
7. Stop
Here's a Python program that implements this algorithm:
# Python program to add two entered numbers
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
# Calculate the sum
sum = num1 + num2
# Display the result
print(f "The sum of {num1} and {num2} is: {sum} ")
Q.2 Define flow chart. Discuss its various blocks with suitable example.
Solution:
Flowchart: A flowchart is a visual representation of an algorithm or process using various symbols to denote
different actions, decisions, and control flow. Flowcharts are excellent for illustrating complex processes and the
flow of logic. For example, here's a simple flowchart for the same "find maximum" algorithm:
Processing: A box represents arithmetic instructions. All arithmetic processes such as adding, subtracting,
multiplication and division are indicated by action or process symbol.
Decision Diamond symbol represents a decision point. Decision based operations such as yes/no question
or true/false are indicated by diamond in flowchart.
Connectors: Whenever flowchart becomes complex or it spreads over more than one page, it is useful to
use connectors to avoid any confusions. It is represented by a circle.
Flow lines: Flow lines indicate the exact sequence in which instructions are executed. Arrows represent the
direction of flow of control and relationship among different symbols of flowchart.
Rules For Creating Flowchart:
A flowchart is a graphical representation of an algorithm. it should follow some rules while creating a
flowchart
Rule 1: Flowchart opening statement must be ‘start’ keyword.
Rule 2: Flowchart ending statement must be ‘end’ keyword.
Rule 3: All symbols in the flowchart must be connected with an arrow line.
Rule 4: The decision symbol in the flowchart is associated with the arrow line.
1. Start
2. Input the principal amount (P), interest rate (R), and time period (T) in years.
3. Calculate simple interest (SI) using the formula: SI = (P * R * T) / 100.
4. Display the calculated simple interest (SI).
5. End.
Q.4 Draw flow chart and Algorithm for the program to find Odd and Even numbers.
Solution:
Algorithm to Find Odd and Even Numbers:
1. Start
2. Input a number (N).
3. Check if N is divisible by 2 without a remainder (N % 2 == 0).
4. If the condition is true, it's an even number; otherwise, it's an odd number.
5. Display the result.
6. End.
Python Program to Find Odd and Even Numbers:
# Input a number
N = int(input("Enter a number: "))
# Check if the number is even or odd
if N % 2 == 0:
result = "Even"
else:
result = "Odd"
# Display the result
print(f"{N} is {result}.")
Flowchart for Finding Odd and Even Numbers:
Q.5 Write an algorithm & draw flowchart to find greatest between 3 numbers.
Solution:
Algorithm to Find the Greatest Among Three Numbers:
1. Start
2. Input three numbers (A, B, C).
3. Compare A with B and find the maximum between A and B max(A,B).
4. Compare max(A,B) with C and find the maximum between max(A,B) and C i.e. max(A,B,C).
5. Display the maximum value, which is max(A,B,C).
6. End.
Python Program to Find the Greatest Among Three Numbers:
Q.6 Write a Program to check the greater number among three number using if-elif-else
statement.
Solution:
Algorithm to Check the Greatest Number Among Three Numbers:
1. Start
2. Input three numbers (A, B, C).
3. Compare A with B.
4. If A is greater than B, compare A with C.
5. If A is also greater than C, then A is the greatest number.
6. If A is not greater than C, then C is the greatest number.
7. If A is not greater than B, compare B with C.
8. If B is greater than C, then B is the greatest number.
9. If B is not greater than C, then C is the greatest number.
10. Display the greatest number.
11. End.
Python Program to Check the Greatest Number Among Three Numbers using if-elif-else:
Q.7 Write an algorithm, program & draw flowchart to calculate area of circle & rectangle.
Solution:
Algorithm to Calculate the Area of a Circle:
1. Start
2. Input the radius of the circle (r).
3. Calculate the area of the circle using the formula: area = π * r^2.
4. Display the calculated area.
5. End.
Python Program to Calculate the Area of a Circle:
# Input the radius of the circle
r = float(input("Enter the radius of the circle: "))
# Calculate the area of the circle
area = 3.142 * (r ** 2)
# Display the area of the circle
print("The area of the circle is:", area)
Flow Chart to Calculate the Area of a Circle:
Q.8 Explain different data types used in python with suitable example
Solution:
Data Types:
In Python, data types are classifications or categories of data that help the interpreter understand how to handle
and manipulate the values we work with in programs. Data types define the type of data a variable can hold, and
they determine what operations can be performed on those values. Python is dynamically typed, which means that
we don't need to explicitly specify the data type of a variable; the interpreter infers the data type based on the value
assigned to the variable.
Python comes with six standard data types out of the box. They are as follows:
Strings
Numbers
Booleans
Lists
Tuples
Dictionaries
Strings (str)
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.
name = "John"
message = 'Hello, World!'
Numbers
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 integer, float and complex.
Integers (int)– 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.
x=5
y = -10
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.
pi = 3.14159
Complex Numbers – Complex number is represented by a complex class. It is specified as (real part) +
(imaginary part)j. For example – 2+3j
Boolean
Boolean variables are used to store Boolean values. True and False are the two Boolean values in Python.
In Python, the bool data type is used to represent Boolean values, which can be either True or False. Boolean
values are often used in conditional statements and logical operations to control the flow of a program. Here's a
brief overview of the bool data type in Python:
1. True and False: These are the two Boolean literals in Python. They are case-sensitive, so we must use a
capital 'T' for True and a capital 'F' for False.
Example:
x = True
y = False
Lists
In Python, a list is a built-in data structure used to store a collection of items. Lists are ordered, mutable (meaning
we can change their contents), and allow duplicate elements. Lists are defined by enclosing a comma-separated
sequence of values in square brackets [ ].
The List data form in Python is used to store a set of values. In every other programming language, lists are
identical to arrays. Python lists, on the other hand, can store values of various types. Opening and closing square
brackets are used to build a list. A comma separates each item in the list from the next. Consider the following
example.
In the script below we created a list named cars. The list contains six string values i.e. car names.
Tuples
In Python, a Tuple is a built-in data structure that is similar to a list in many ways. However, there is one key
difference: tuples are immutable, while lists are mutable. This means that once we create a tuple, we cannot
change its contents (add, remove, or modify elements). Tuples are defined by enclosing a comma-separated
sequence of values within parentheses () or by using a comma-separated sequence of values without any enclosing
parentheses.
Tuples are similar to Lists, but there are two main distinctions. To begin, instead of using square brackets to create
lists, opening and closing braces are used to create tuples. Second, once formed, a tuple is permanent, which
means that its values cannot be changed. This definition is illustrated in the following illustration.
Here's an overview of tuples in Python:
cars = ['Honda', 'Toyota', 'Audi', 'Ford', 'Suzuki', 'Mercedez'] #List
cars2 = ('Honda', 'Toyota', 'Audi', 'Ford', 'Suzuki', 'Mercedez') # Tuple
Dictionaries
In Python, a Dictionary is a built-in data structure that allows we to store a collection of key-value pairs.
Dictionaries are collections of data that are stored in the form of key-value
pairs. A comma separates each key-value pair from the next. Each key is associated with a corresponding value,
and dictionaries are often used when we want to access and manipulate data using a meaningful key rather than an
index. Dictionaries are defined using curly braces { } and consist of key-value pairs separated by colons: Indexes
and keys can also be used to access dictionary objects.
Q.9 Define a function. Also explain how to create a function in python with example.
Q.9What is function? Explain its significance in programming. Define its syntax.
Q.9Explain function syntax, function definition, calling function, parameter &
argument with suitable python function
Solution:
Functions:
A function in Python is a block of reusable code that performs a specific task or set of tasks. Functions allow we to
encapsulate code and provide a way to call and reuse it with different inputs.
Here's how we can define and use a function:
1. Defining a Function:
We can define a function using the def keyword, followed by the function name and its parameters (if any):
def greet(name):
return f"Hello, {name}!"
2. Calling a Function:
To use a function, we call it by its name and provide the required arguments (if any):
message = greet("Charlie")
print(message) # Output: "Hello, Charlie!"
Function Parameters:
Functions can have parameters (inputs) that allow we to pass values into the function. These values are used inside
the function to perform computations or actions.
Return Values:
Functions can return values using the return statement. The returned value can be stored in a variable or used
directly in code.
def multiply(a, b):
return a * b
product = multiply(4, 6)
print(product) # Output: 24
Parameters and Arguments:
In Python, the terms "parameters" and "arguments" are often used in the context of functions, and they refer to
different aspects of passing information to a function. Here's a breakdown of what each term means:
Parameters:
Parameters are variables defined in the function's declaration or definition. They act as placeholders for values that
the function expects to receive when it is called. Parameters are used to specify the type and number of values that
the function will accept. Parameters are part of the function's signature and are defined inside the parentheses
following the function name.
Example
def greet(name): # 'name' is a parameter
print(f"Hello, {name}!")
def add(x, y): # 'x' and 'y' are parameters
return x + y
Arguments:
Arguments, on the other hand, are the actual values or expressions that are passed to a function when it is called.
Arguments are used to provide specific data or input to the function, and they correspond to the parameters
defined in the function's signature. When we call a function, we supply arguments that match the order and type of
the parameters defined in the function.
Example
greet("Alice") # "Alice" is an argument passed to the 'name' parameter
result = add(3, 5) # 3 and 5 are arguments passed to the 'x' and 'y' parameters
In summary, parameters are variables defined in a function's signature, serving as placeholders for expected
values, while arguments are the actual values or expressions passed to a function when it is called. Arguments are
used to provide input to the function and match the parameters defined in the function's signature
Q.10 Write a program for function to print square of numbers in list. eg.
numbers=[1,2,3,4,5] result should be [1,4,9,16,25]
Solution:
def square_numbers(numbers):
squared_list = [number ** 2 for number in numbers]
return squared_list
numbers = [1, 2, 3, 4, 5]
result = square_numbers(numbers)
# Print the squared numbers
print(result)
Q.11 Write a program to print Fibonacci series using for loop/ while loop.
Solution:
Python program to print the Fibonacci series using a for loop:
Q.12 Explain scope of local and global variable with suitable example.
Solution:
In Python, variables can have different scopes, primarily categorized into two main types: local and global.
1. Local Variables:
Local variables are defined within a function and are only accessible within that function.
They have a limited scope and are not visible or usable outside the function.
Local variables are created when the function is called and destroyed when the function exits.
Here's an example of a local variable in Python:
def my_function():
# This is a local variable
x = 10
print("Inside the function: x =", x)
my_function()
In this example, x is a local variable within the my_function function. You can access and use x within the
function, but if we will try to access it outside the function, we will get an error.
2. Global Variables:
Global variables are defined outside of any function and are accessible from any part of the code, both
inside and outside functions.
They have a broader scope and can be used throughout the entire program.
Here's an example of a global variable in Python:
# This is a global variable
y = 20
def my_function():
# Accessing the global variable within the function
print("Inside the function: y =", y)
my_function()
# We can also access y outside the function
print("Outside the function: y =", y)
In this example, y is a global variable defined outside the function my_function. We can access y both inside and
outside the function without any issues.
It's important to note that if we want to modify the value of a global variable from within a function, we need to
use the global keyword to indicate that we are working with the global variable. Here's an example:
z = 30
def modify_global_variable():
global z # Use the 'global' keyword to modify the global variable
z = 40
modify_global_variable()
print("Modified global variable z =", z)
In this example, we use the global keyword to inform Python that we want to modify the global variable z from
within the function. As a result, the value of z is changed to 40.
Q.13 Explain the concept of recursion by writing function to compute the factorial of
given number.
Solution:
Recursion is a programming technique where a function calls itself in order to solve a problem. It's a powerful and
elegant way to solve certain types of problems, and it's often used when a problem can be broken down into
smaller, similar sub-problems.
One classic example of recursion is calculating the factorial of a given number. The factorial of a non-negative
integer n, denoted as n!, is the product of all positive integers from 1 to n. Mathematically, it's defined as:
n! = 1, if n = 0
n! = n * (n-1)! if n > 0
In this definition, we can see the recursive nature of the factorial function. Here's a Python function to
calculate the factorial of a given number using recursion:
def factorial(n):
if n == 0:
return 1
else:
# The factorial of n is n times the factorial of (n-1)
return n * factorial(n - 1)
In this function:
1. We check if n is equal to 0. If it is, we return 1 because 0! is defined as 1.
2. If n is not 0, we calculate the factorial of n by calling the factorial function recursively with the argument
n - 1. This recursive call will continue until n becomes 0, and then the base case will be reached, and the
recursion will start to "unwind" by multiplying the values back up to the original n, giving us the factorial.
We can call this function with a specific number to find its factorial. For example:
print(factorial(5)) # This will print 120, which is 5!
The function will work for any non-negative integer value of n and will calculate its factorial using recursion.
# You can omit the start index. It will start from the beginning of the string.
substring2 = text[:5]
print(substring2) # Output: "Hello"
# Extract a substring starting at index 7 and ending at the end of the string.
substring3 = text[7:]
print(substring3) # Output: "World!"
Q.15 Write a program to create a list of five elements and apply to update and delete the list.
Solution:
Python program that creates a list of five elements, updates elements within the list, and deletes elements from the
list:
# Create a list of five elements
my_list = [10, 20, 30, 40, 50]
print("Original list:", my_list)
Q.17 Write a program to create a dictionary and access the items of dictionary using for
loop.
Solution:
Python program that creates a dictionary and accesses its items using a for loop:
# Create a dictionary
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
Lists and dictionaries are two different data structures in Python, each with its own set of properties and
characteristics.
Properties of Lists:
1. Ordered: Lists are ordered collections of items, meaning the elements are stored in a specific sequence and
can be accessed by their index.
2. Mutable: Lists are mutable, which means you can add, remove, or modify elements after creating a list.
3. Heterogeneous: Lists can contain a mix of different data types, including integers, strings, floats, and even
other lists.
4. Access by Index: You can access list elements using their index, with indexing starting at 0.
5. Slicing: Lists support slicing, allowing you to extract specific ranges or subsets of elements from a list.
6. Dynamic Size: Lists can grow or shrink in size as you add or remove elements.
7. Support for Common Operations: Lists provide various methods for common operations like appending,
extending, and sorting.
Example:
my_list = [1, 'apple', 3.14, [4, 5]]
Properties of Dictionaries:
1. Unordered: Dictionaries are unordered collections of key-value pairs. They don't have a specific sequence.
2. Mutable: Dictionaries are mutable, allowing you to add, update, or remove key-value pairs.
3. Keys are Unique: Dictionary keys must be unique. If you try to add a duplicate key, the old value associated
with it is overwritten.
4. Keys are Immutable: Keys must be of an immutable data type, such as strings, numbers, or tuples.
5. Values Can Be Heterogeneous: The values associated with keys can be of different data types.
6. Access by Key: You access dictionary values using their associated keys, not by index.
7. No Duplicate Keys: Dictionaries do not allow duplicate keys. If you try to add the same key multiple times,
only the last value assigned to that key will be stored.
8. Common Dictionary Operations: Dictionaries support operations like adding key-value pairs, deleting key-
value pairs, checking for key existence, and iterating through keys or values.
In summary, lists are ordered and allow access by index, while dictionaries are unordered and use keys to access
values. Lists are typically used for collections of items where the order matters, while dictionaries are used for
storing key-value pairs, making it easy to look up values by a specific key.
Q.18 Explain the concept of object oriented programming using suitable example.
Solution:
Object-oriented programming (OOP) is a method of structuring a program by bundling related properties and
behaviors into individual objects.
Object-oriented programming in Python is a powerful and flexible way to structure and organize your code. It
helps you model real-world concepts and relationships between objects, making your code more maintainable and
easier to understand.
Object-oriented programming (OOP) is a programming paradigm that is based on the concept of "objects." Objects
are instances of classes, and they can contain both data (attributes) and behavior (methods). Python is a versatile
programming language that supports OOP principles. Here's an overview of how you can use OOP in Python:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
Attributes:
Objects can have attributes that store data.
We can access and modify object attributes using dot notation.
print(person1.name)
print(person1.age)
print(person2.name)
print(person2.age)
# Output: Alice
30
Bob
25
Methods:
Methods are functions defined within a class. They can operate on the object's data (attributes).
The self parameter is used to refer to the instance of the object inside the class methods.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def say_hello(self):
print("Hello, my name is {self.name} and I'm {self.age} years old.")
Inheritance:
Inheritance allows you to create a new class that is a modified version of an existing class. The new class inherits
attributes and methods from the base class.
class Student(Person):
def __init__(self, name, age, student_id):
super().__init__(name, age)
self.student_id = student_id
1. Encapsulation:
You can use encapsulation to control the visibility of attributes and methods within a class.
By convention, attributes and methods that should not be accessed from outside the class are prefixed with a
single underscore (e.g., _private_var) to indicate that they are for internal use.
2. Polymorphism:
Polymorphism allows you to use the same interface (method name) for objects of different classes.
It simplifies the code and allows you to work with objects in a more abstract and generic way.
def introduce(person):
person.say_hello()
Q.19 Explain various types of exception handling using suitable syntax and example.
Solution:
Exception
An exception is an occurrence that causes the program's execution to be
interrupted. In other words, when a Python script meets a condition that it is unable to handle, it throws an
exception. Exceptions in Python are raised in the form of objects. When an exception occurs, an object containing
information about the exception is initialized. In Python, an exception must be addressed or the program may
terminate.
Exception Handling in Python
Exception handling in Python allows us to handle and recover from errors or exceptional situations that can occur
during the execution of our code. These exceptional situations are known as exceptions. Python provides a
mechanism to catch and manage exceptions to prevent our program from crashing when something unexpected
happens.
Syntax for Exception Handing
The syntax for exception handling is as follows:
try:
#the code that can raise exception
except ExceptionA:
#the code to execute if ExceptionA occurs
For example:
try:
x = 10 / 0
except ZeroDivisionError:
print("Division by zero is not allowed.")
Output: Division by zero is not allowed
Multiple Exceptions
We can handle different types of exceptions separately by using multiple except blocks.
Syntax
try:
# Code that might raise an exception
except ExceptionType1:
# Handle ExceptionType1
except ExceptionType2:
# Handle ExceptionType2
except ExceptionType3:
# Handle ExceptionType3
Example
To manage multiple exceptions, simply stack one exception handling block on top of the other. Consider the
following exception:
Exam
try:
num1 = 10
num2 = 2
result = num1/num2
print(result)
except ZeroDivisionError:
print ("Sorry, division by zero not possible")
except NameError:
Another way to handle multiple exceptions is by using Exception object which is base class for all the exceptions.
The Exception object can be used to handle all types of exceptions. Take a look at the following example.
try:
num1 = 10
num2 = 0
result = num1/num2
print(result)
except Exception:
print ("Sorry, program cannot continue")
else:
Q.20 Briefly define file handling in Python. Write a program to open, write, read and close
the python file.
Solution:
Python File Handling
File handling or data handling is the process of performing various operations on various types of files. The most
popular file operations are opening a file, reading the contents of a file, creating a file, writing data to a file,
appending data to a file, etc.
1. Opening a File
To open a file in python the open function is used. It takes 3 parameters: The path to the file, the mode in which
the file should be opened and the buffer size in number of lines. The third parameter is optional. The open function
returns file object. The syntax of the open function is as follows:
Example:
First create a file test.txt and place it in the root directory of the D drive.
print(file_object.mode)
print(file_object.closed)
In the script above, we open the test.txt file in the read and write mode. Next we print the name and mode of the
file on the screen. Finally we print whether the file is closed or not.
Output:
D:/test.txt
r+
False
1. Close a File
To close an opened file, we can use close method.
Example:
file_object=open("D:/test.txt","r+")
print(file_object.name)
print(file_object.closed)
file_object.close()
print(file_object.closed)
In the script above, the test.txt file is opened in r+ mode. The name of the file is printed. Next we check if the file
is opened using closed attribute, which returns false, since the file is open at the moment. We then close the file
using close method. We again check if the file is closed, which returns true since we have closed the file.
Output:
D:/test.txt
False
True
2. Writing Data to a File
To write data to a file, the write function is used. The content that is to be written to the file is passed as parameter
to the write function.
Example:
file_object .close()
In the script above, the file test.txt located at the root directory of D drive is opened. The file is opened for reading
and writing. Next two lines of text have been passed to the write function. Finally the file is closed.
If we will go to root directory of D drive, we will see a new file test1.txt with the following contents:
Welcome to Python.
The best programming language!
Example:
file_object = open("D:/test1.txt", "r+")
sen = file_object.read(12)
print("The file reads: "+sen)
file_object .close()
The script above reads the first 12 characters from the test1.txt file that we wrote in the last example.
Output:
The file reads: Welcome to P
To read the complete file, do not pass anything to the read function. The following script reads the complete
test1.txt file and prints its total content.
file_object = open("D:/test1.txt", "r+")
sen = file_object.read()
print(sen)
file_object .close()
Output:
Welcome to Python.
The best programming language!
Don’t Forget