0% found this document useful (0 votes)
120 views26 pages

Exam Score Booster

Uploaded by

hrishikapatel946
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)
120 views26 pages

Exam Score Booster

Uploaded by

hrishikapatel946
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/ 26

EXAM SCORE BOOSTER

Programming for Problem Solving [UNITL102]

Q.1 Define algorithm? Discuss its various building blocks of algorithm.


Solution:
Algorithms are step-by-step sets of instructions or procedures for solving a specific problem or performing a
particular task. They serve as a blueprint for solving problems, and they can be found in various aspects of
computer science, mathematics, and everyday life. Algorithms are fundamental to computer programming because
they define how a computer should perform a task or make a decision.
Here's a simple algorithm to add two numbers that are entered by the user:

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} ")

BUILDING BLOCKS OF ALGORITHM


The building blocks of algorithms can be broken down into several key components:
1. Statements: Statements are individual instructions that perform specific actions. They are the basic building
blocks of algorithms and can include operations like assignment (e.g., x = 5), arithmetic calculations (e.g., y =
x + 3), and conditional statements (e.g.,
if x > 0:
print("x is positive")).
2. State: State refers to the current condition or values of variables at a particular point in the algorithm's
execution. Variables store data that the algorithm uses to perform calculations and make decisions. Managing
the state effectively is crucial in designing algorithms.
3. Control Flow: Control flow defines the order in which statements are executed in an algorithm. Common
control flow constructs include sequence (statements executed one after the other), selection (conditional
execution based on a condition, e.g., if-else statements), and iteration (repeating a set of statements, e.g.,
loops).
if num1 > num2:
return num1
else:
return num2
4. Functions: Functions are reusable blocks of code that encapsulate a specific task or set of instructions. They
allow you to break down a complex problem into smaller, more manageable parts. Functions take input,
perform operations, and can produce output. Functions are essential for modularizing code and promoting code
reusability.

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:

Flowchart is a graphical representation of an algorithm. Programmers often use it as a program-planning tool to


solve a problem. It makes use of symbols which are connected among them to indicate the flow of information and
processing.
The process of drawing a flowchart for an algorithm is known as “flowcharting”.
Basic Symbols used in Flowchart Designs
 Terminal: The oval symbol indicates Start, Stop and Halt in a program’s logic flow. A pause/halt is generally
used in a program logic under some error conditions. Terminal is the first and last symbols in the flowchart.
 Input/ Output: A parallelogram denotes any function of input/output type. Program instructions that take
input from input devices and display output on output devices are indicated with parallelogram in a flowchart.

 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.

Q.3 Write Program, Algorithm & Draw flowchart of Simple Interest.


Solution:
Python Program for Calculating Simple Interest:

# Input principal amount, interest rate, and time period


P = float(input("Enter the principal amount: "))
R = float(input("Enter the interest rate (in percentage): "))
T = float(input("Enter the time period (in years): "))
# Calculate simple interest
SI = (P * R * T) / 100
# Display the calculated simple interest
print("Simple Interest:", SI)

Algorithm for Calculating Simple Interest:

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:

# Input three numbers


A = float(input("Enter the first number: "))
B = float(input("Enter the second number: "))
C = float(input("Enter the third number: "))
# Find the maximum between A and B
maxAB = max(A, B)
# Find the maximum among A, B, and C
maxABC = max(maxAB, C)
# Display the maximum value
print("The greatest number is:", maxABC)

Flow Chart 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:

# Input three numbers


A = float(input("Enter the first number: "))
B = float(input("Enter the second number: "))
C = float(input("Enter the third number: "))
# Check which number is the greatest
if A > B:
if A > C:
greatest = A
else: greatest = C
elif B > C:
greatest = B
else:
greatest = C
# Display the greatest number
print("The greatest number is:", greatest)

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.

cars = ['Honda', 'Toyota', 'Audi', 'Ford', 'Suzuki', 'Mercedez']


print(len(cars)) #finds total items in string
print(cars) # print the list

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.

Here's an overview of dictionaries in Python:


cars = {'Name':'Audi', 'Model': 2008, 'Color':'Black'}

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.

def add(x, y):


return x + y
result = add(3, 5)
print(result) # Output: 8
Functions can be defined in modules and imported into other scripts for reuse, making them a poful tool for code
organization and reuse in Python. They are essential for breaking down complex tasks into manageable parts and
improving the readability and maintainability of code.

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:

# Function to print the Fibonacci series using a for loop


def fibonacci (n):
a, b = 0, 1
for i in range(n):
print(a, end=" ")
a, b = b, a + b
# Input the number of terms in the series
n = int(input("Enter the number of terms: "))
# Check if the input is valid
if n <= 0:
print("Please enter a positive integer.")
else:
print("Fibonacci Series (using for loop):")
fibonacci (n)
Python program to print the Fibonacci series using a while loop:

# Function to print the Fibonacci series using a while loop


def fibonacci (n):
a, b = 0, 1
count = 0
while count < n:
print(a, end=" ")
a, b = b, a + b
count += 1

# Input the number of terms in the series


n = int(input("Enter the number of terms: "))
# Check if the input is valid
if n <= 0:
print("Please enter a positive integer.")
else:
print("Fibonacci Series (using while loop):")
fibonacci (n)

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.

Q.14 Explain slicing of string using suitable example.


Solution:
Slicing is a technique in Python that allows you to extract a portion of a string or any other sequence (such as a list
or tuple) by specifying a start index, an end index, and an optional step size. It is a very useful and versatile way to
work with substrings.
The syntax for slicing a string is as follows:
string[start:end:step]

 start: The index at which the slice begins (inclusive).


 end: The index at which the slice ends (exclusive).
 step (optional): The step size or increment between characters in the slice.
Here's an example to illustrate string slicing:

text = "Hello, World!"

# Extract a substring starting at index 0 and ending at index 5 (exclusive).


substring1 = text[0:5]
print(substring1) # Output: "Hello"

# 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!"

# Use negative indices to count from the end of the string.


substring4 = text[-6:]
print(substring4) # Output: "World!"

# Extract every other character from the string.


substring5 = text[::2]
print(substring5) # Output: "Hlo ol!"

# Reverse the string using a step size of -1.


substring6 = text[::-1]
print(substring6) # Output: "!dlroW ,olleH"

In the examples above:


 substring1 extracts the characters from index 0 to 4, resulting in "Hello."
 substring2 omits the start index, effectively starting from the beginning of the string.
 substring3 extracts the characters from index 7 to the end of the string, resulting in "World!"
 substring4 uses negative indexing to achieve the same result.
 substring5 uses a step size of 2 to extract every other character.
 substring6 uses a step size of -1 to reverse the string.
String slicing is a convenient way to manipulate and extract substrings from strings in Python.

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)

# Update an element at a specific index


my_list[2] = 35
print("List after updating an element at index 2:", my_list)

# Add an element to the end of the list using append()


my_list.append(60)
print("List after appending an element:", my_list)

# Insert an element at a specific index


my_list.insert(1, 15)
print("List after inserting an element at index 1:", my_list)

# Remove an element by its value using remove()


my_list.remove(40)
print("List after removing the element 40:", my_list)

# Delete an element by its index using del


del my_list[3]
print("List after deleting the element at index 3:", my_list)
# Pop an element from the list by index using pop()
popped_element = my_list.pop(0)
print("List after popping the element at index 0:", my_list)
print("Popped element:", popped_element)

# Clear the entire list


my_list.clear()
print("List after clearing:", my_list)
In this program:
 We create an initial list my_list with five elements.
 We update an element at a specific index by assigning a new value to it.
 We add an element to the end of the list using the append() method.
 We insert an element at a specific index using the insert() method.
 We remove an element by its value using the remove() method.
 We delete an element by its index using the del statement.
 We pop an element from the list by its index using the pop() method. The popped element is also displayed.
 We clear the entire list using the clear() method.

Q.16 Write a program to show the different operations on Dictionary


Solution:
Python dictionaries are versatile data structures that allow you to perform various operations. Here's a Python
program that demonstrates different operations on dictionaries:
# Creating an empty dictionary
my_dict = {}

# Adding key-value pairs to the dictionary


my_dict['name'] = 'John'
my_dict['age'] = 30
my_dict['city'] = 'New York'

# Display the dictionary


print("Original Dictionary:")
print(my_dict)

# Accessing values by key


name = my_dict['name']
print("Name:", name)
# Checking if a key exists in the dictionary
if 'age' in my_dict:
print("Age is present in the dictionary.")

# Getting the list of keys and values


keys = my_dict.keys()
values = my_dict.values()
print("Keys:", list(keys))
print("Values:", list(values))

# Removing a key-value pair by key using 'del'


del my_dict['city']
print("Dictionary after deleting 'city':")
print(my_dict)

# Removing a key-value pair by key using 'pop'


age = my_dict.pop('age')
print("Dictionary after popping 'age':")
print(my_dict)
print("Popped age:", age)

# Clearing the dictionary


my_dict.clear()
print("Dictionary after clearing:")
print(my_dict)

# Creating a dictionary with initial key-value pairs


new_dict = {'country': 'USA', 'population': 331000000}

# Merging two dictionaries using update()


my_dict.update(new_dict)
print("Merged Dictionary:")
print(my_dict)

# Iterating through key-value pairs in the dictionary


print("Iterating through key-value pairs:")
for key, value in my_dict.items():
print(key, ":", value)
In this program:
1. We create an empty dictionary my_dict and add key-value pairs to it.
2. We access values in the dictionary by their keys.
3. We check if a key exists in the dictionary using the in keyword.
4. We retrieve the list of keys and values in the dictionary using keys() and values() methods.
5. We remove key-value pairs from the dictionary using the del statement and the pop() method.
6. We clear the entire dictionary using the clear() method.
7. We merge two dictionaries using the update() method.
8. We iterate through key-value pairs in the dictionary using a for loop.

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'}

# Access dictionary items using a for loop


print("Accessing dictionary items using a for loop:")
for key in my_dict:
value = my_dict[key]
print(key, ":", value)
In this program:
1. We create a dictionary called my_dict with three key-value pairs.
2. We use a for loop to iterate through the keys of the dictionary. In each iteration, we access the value
associated with the current key using my_dict[key].
3. The loop prints out the key and its corresponding value.

Q. 18 Describe the properties of list and dictionary.


Solution:

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.

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}

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:

Classes and Objects:


 In Python, you define a class using the class keyword. A class is a blueprint for creating objects.
 Objects are instances of classes. You create an object by calling the class as if it were a function.

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

person1 = Person("Alice", 30)


person2 = Person("Bob", 25)

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.")

person1 = Person("Alice", 30)


person1.say_hello()
# Output: "Hello, my name is Alice and I'm 30 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

student = Student("Eve", 20, "12345")


student.say_hello() # Student inherits the say_hello() method from the Person class.

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()

alice = Person("Alice", 30)


bob = Student("Bob", 25, "98765")

introduce(alice) # Output: "Hello, my name is Alice and I'm 30 years old."


introduce(bob) # Output: "Hello, my name is Bob and I'm 25 years old."

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:

print ("Some variable/s are not defined")


else:
print("Program executed without an exception")
In the script above, both the “ZeroDivisionError” and “NameError” exceptions are handled. Therefore, if you set
the value of num2 to 0, the “ZeroDivisionError” exception will occur. However if you try to divide the num1 by
‘b’, the “NameError” exception will occur since the variable “b” is not defined. Finally if none of the exception
occurs, the statement in the
else block will execute.

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:

print("Program executed without an exception")


In the script above, all the different types of exceptions will be handled by code block for Exception object.
Therefore, a generic message will be printed to the user. In the script above, the num2 contains zero. Therefore,
the “ZeroDivisionError” exception will occur. The result will look like this:

Sorry, program cannot continue

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:

file_object = open(file_name, file_mode, buffer_size)


The file object returned by the open method has three main attributes:
1- name: returns the name of the file
2- mode: returns the mode with which the file was opened
3- closed: is the file closed or not

Example:
First create a file test.txt and place it in the root directory of the D drive.

file_object = open("D:/test.txt", "r+")


print(file_object.name)

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 = open("D:/test1.txt", "w+")


file_object .write( "Welcome to Python.\n The best programming language! \n")

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!

3. Reading Data from a File:


To read data from a file in Python, the read function is used. The number of bytes to read from a file is passed as a
parameter to the read function.

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

There is NO SUBSTITUTE of HARDWORK


If there is NO STRUGGLE, there is NO PROGRESS.

You might also like