0% found this document useful (0 votes)
7 views47 pages

PSP

The document provides a comprehensive overview of algorithms, including definitions, building blocks, and characteristics of good algorithms. It covers various topics such as flowcharts, recursion, iteration, and control statements in Python, along with examples and pseudocode for specific problems. Additionally, it includes Python programs for tasks like finding the factorial, checking for prime numbers, and manipulating strings.

Uploaded by

budoduai
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)
7 views47 pages

PSP

The document provides a comprehensive overview of algorithms, including definitions, building blocks, and characteristics of good algorithms. It covers various topics such as flowcharts, recursion, iteration, and control statements in Python, along with examples and pseudocode for specific problems. Additionally, it includes Python programs for tasks like finding the factorial, checking for prime numbers, and manipulating strings.

Uploaded by

budoduai
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

Q1. Define algorithm and explain building blocks of algorithm.

(2 Marks)

Algorithm:
An algorithm is a finite sequence of well-defined steps used to solve a problem or perform a computation.

Building blocks of an algorithm:

1. Input – Data given to the algorithm

2. Processing – Logical operations performed on data

3. Output – Result produced after processing

**Q2. Explain the following building blocks of algorithm:

(i) Statements (ii) Control flow (2 Marks)**

(i) Statements:
Statements are individual instructions in an algorithm that perform actions such as assignment, input, or
output.

(ii) Control flow:


Control flow determines the order of execution of statements using sequence, selection (if), and iteration
(loops).

Q3. What is an algorithm? List the characteristics of a good algorithm. (2 Marks)

Algorithm:
An algorithm is a step-by-step procedure for solving a problem in a finite amount of time.

Characteristics of a good algorithm:

1. Finite – Must terminate after a limited number of steps

2. Unambiguous – Each step should be clearly defined

Q4. Identify simple strategies for developing an algorithm. (2 Marks)

Simple strategies for developing an algorithm are:

1. Divide and Conquer – Break the problem into smaller parts

2. Step-by-step refinement – Develop the solution gradually from simple to detailed steps

Q5. Write an algorithm that calculates the salary of an employee. (2 Marks)

Algorithm to calculate Gross Salary:

1. Start

2. Read Basic salary, HRA, TA, DA

3. Gross Salary = Basic + HRA + TA + DA

4. Display Gross Salary


5. Stop

Q6. Write an algorithm for the following: (8 Marks)

(i) Calculating area and circumference of a circle

(ii) Check if a given year is a leap year or not

(i) Algorithm to calculate Area and Circumference of a Circle

1. Start

2. Read radius r

3. Area = π × r × r

4. Circumference = 2 × π × r

5. Display Area and Circumference

6. Stop

(ii) Algorithm to check Leap Year

1. Start

2. Read year y

3. If (y % 400 == 0) then
Print “Leap Year”

4. Else if (y % 100 == 0) then


Print “Not a Leap Year”

5. Else if (y % 4 == 0) then
Print “Leap Year”

6. Else
Print “Not a Leap Year”

7. Stop

Q7. Explain Towers of Hanoi. Write the Pseudocode for Towers of Hanoi. (8 Marks)

Explanation:

The Towers of Hanoi is a classical problem involving three rods and n disks.
The objective is to move all disks from the source rod to the destination rod following these rules:

• Only one disk can be moved at a time

• A larger disk cannot be placed on a smaller disk

Pseudocode for Towers of Hanoi

TOH(n, source, auxiliary, destination)

If n == 1
Move disk from source to destination

Else

TOH(n-1, source, destination, auxiliary)

Move disk from source to destination

TOH(n-1, auxiliary, source, destination)

End If

Q8. Outline the Towers of Hanoi problem. Suggest a solution with relevant diagrams. (8 Marks)

Outline:

• The problem consists of three pegs: Source, Auxiliary, Destination

• Initially, all disks are placed on the source peg in decreasing size

• Goal is to move all disks to the destination peg

Solution Strategy:

1. Move n−1 disks from source to auxiliary

2. Move the largest disk from source to destination

3. Move n−1 disks from auxiliary to destination

Key Point:

The problem is solved efficiently using recursion.

**Q9. (i) Summarize the advantages and disadvantages of flowchart

(ii) Summarize the symbols used in flowchart. (8 Marks)**

(i) Advantages of Flowchart

• Easy to understand

• Improves problem analysis

• Helps in debugging

Disadvantages of Flowchart

• Time-consuming to draw

• Difficult to modify

• Not suitable for complex programs

(ii) Flowchart Symbols

Symbol Name Purpose

Oval Terminal Start/Stop


Symbol Name Purpose

Parallelogram Input/Output Read/Print

Rectangle Process Computation

Diamond Decision Yes/No

Arrow Flow line Direction of flow

**Q10. (i) Develop a flowchart to check whether a number is prime or not

(ii) Develop a pseudocode to perform arithmetic operations. (8 Marks)**

(i) Flowchart – Prime Number (Explanation form)

1. Start

2. Read number n

3. Set i = 2

4. If n ≤ 1 → Not Prime

5. If n % i == 0 → Not Prime

6. Increment i and repeat until i < n

7. Else → Prime

8. Stop

(ii) Pseudocode for Arithmetic Operations

Start

Read a, b

Sum = a + b

Difference = a - b

Product = a * b

Quotient = a / b

Display results

Stop

**Q11. (i) What is a flowchart? List symbols and rules for writing flowchart

(ii) Draw a flowchart to count and print from 1 to 10. (8 Marks)**

(i) Flowchart

A flowchart is a graphical representation of an algorithm using standard symbols to show the sequence of
steps in solving a problem.

Flowchart Symbols
Symbol Name Use

Oval Terminal Start / Stop

Rectangle Process Calculations

Parallelogram Input/Output Read / Print

Diamond Decision Yes / No

Arrow Flow line Direction of flow

Rules for Flowchart

• Flow should be from top to bottom

• Use standard symbols only

• Avoid crossing flow lines

• Each flowchart must have start and stop

(ii) Flowchart to count from 1 to 10 (Steps)

1. Start

2. Set i = 1

3. Print i

4. Increment i = i + 1

5. If i ≤ 10, go to step 3

6. Stop

Q12. Define iteration and recursion. Write an algorithm to find factorial using iteration and recursion. (8
Marks)

Iteration

Iteration is the repeated execution of a block of statements using loops.

Recursion

Recursion is a technique where a function calls itself to solve a problem.

Algorithm: Factorial using Iteration

1. Start

2. Read number n

3. Set fact = 1

4. For i = 1 to n
fact = fact × i

5. Display fact
6. Stop

Algorithm: Factorial using Recursion

1. Start

2. Read number n

3. If n = 0 return 1

4. Else return n × factorial(n−1)

5. Stop

Q13. What is function? Write a program to display largest of three numbers using function. (8 Marks)

Function

A function is a block of reusable code that performs a specific task.

Python Program

def largest(a, b, c):

if a >= b and a >= c:

return a

elif b >= a and b >= c:

return b

else:

return c

x = int(input("Enter first number: "))

y = int(input("Enter second number: "))

z = int(input("Enter third number: "))

print("Largest number is:", largest(x, y, z))

**Q14. (i) Algorithm to find GCD using Euclid’s Algorithm

(ii) Algorithm to generate Fibonacci series using recursion. (8 Marks)**

(i) Algorithm: GCD using Euclid’s Algorithm

1. Start

2. Read numbers a, b
3. While b ≠ 0
r=a%b
a=b
b=r

4. Display a as GCD

5. Stop

(ii) Algorithm: Fibonacci using Recursion

1. Start

2. If n = 0 return 0

3. If n = 1 return 1

4. Else return fib(n−1) + fib(n−2)

5. Stop

Q15. Design Flowchart, Algorithm, Pseudocode for factorial using loop. (8 Marks)

Algorithm

1. Start

2. Read number n

3. Set fact = 1

4. Repeat while n > 0


fact = fact × n
n=n−1

5. Display fact

6. Stop

Pseudocode

START

READ n

fact ← 1

WHILE n > 0

fact ← fact * n

n←n-1

END WHILE

PRINT fact

STOP
Flowchart (Explanation)

Start → Input n → Initialize fact → Loop → Multiply → Decrement → Print → Stop

Q16. Using pseudocode, outline the steps to insert a new card into a sorted list of cards while preserving
the sorted order. (8 Marks)

Pseudocode

START

READ list of sorted cards

READ new_card

SET position = length of list

WHILE position > 0 AND list[position-1] > new_card

list[position] = list[position-1]

position = position - 1

END WHILE

list[position] = new_card

DISPLAY updated list

STOP

Explanation (2–3 lines):

The algorithm shifts larger elements to the right and inserts the new card at the correct position to maintain
sorted order.

Q17. Analyse the iterative solution for the Towers of Hanoi problem and compare it with the recursive
approach. Discuss trade-offs. (8 Marks)

Iterative Solution – Explanation

• Uses loops and stacks instead of recursive calls

• Avoids function call overhead

• More complex to implement

Recursive Solution – Explanation

• Simple and intuitive

• Directly follows the problem definition

• Uses system stack (risk of stack overflow)

Comparison Table
Aspect Recursive Iterative

Simplicity Easy Complex

Memory High (stack) Lower

Speed Moderate Faster

Readability High Low

Conclusion

Recursive approach is preferred for clarity, while iterative is better for efficiency.

Q18. Write an algorithm and design a flowchart to check whether a given number is a perfect number or
not. (8 Marks)

Algorithm

1. Start

2. Read number n

3. Set sum = 0

4. For i = 1 to n−1
If n % i == 0
sum = sum + i

5. If sum == n
Print “Perfect Number”

6. Else
Print “Not a Perfect Number”

7. Stop

Flowchart (Explanation)

Start → Input n → Initialize sum → Loop → Check divisor → Add → Compare sum → Print result → Stop

Q19. Write a Python program to find factorial of a given number using recursion function. (8 Marks)

Python Program

def factorial(n):

if n == 0 or n == 1:

return 1

else:

return n * factorial(n - 1)

num = int(input("Enter a number: "))


print("Factorial is:", factorial(num))

Explanation

The function calls itself until the base condition is met and multiplies values while returning.

**Q20. (i) Describe recursion with example

(ii) Define iteration and explain with example to find sum of first N natural numbers. (8 Marks)**

(i) Recursion

Recursion is a technique where a function calls itself until a base condition is satisfied.

Example: Power of a number

def power(a, n):

if n == 0:

return 1

return a * power(a, n-1)

(ii) Iteration

Iteration repeatedly executes a set of statements using loops.

Example: Sum of first N natural numbers

n = int(input("Enter n: "))

sum = 0

for i in range(1, n+1):

sum += i

print("Sum =", sum)

Q21. List the types of operators in Python. (2 Marks)

The types of operators in Python are:

1. Arithmetic operators

2. Relational (comparison) operators

3. Logical operators

4. Bitwise operators

5. Assignment operators

6. Membership operators

7. Identity operators
Q22. Explain with an example, break statement and continue statement using while loop in Python. (2
Marks)

Break statement:
Terminates the loop immediately when a condition is satisfied.

Continue statement:
Skips the current iteration and continues with the next iteration.

Example:

i=0

while i < 5:

i += 1

if i == 3:

continue

if i == 5:

break

print(i)

Q23. Explain the looping statements in Python. (2 Marks)

Python provides two looping statements:

1. for loop – used to iterate over a sequence

2. while loop – executes repeatedly as long as a condition is true

Q24. (i) Write a Python program to find the greatest among three numbers. (2 Marks)

a = int(input())

b = int(input())

c = int(input())

if a > b and a > c:

print(a)

elif b > c:

print(b)

else:

print(c)

Q25. (ii) Write a Python program to find the sum of N natural numbers. (2 Marks)

n = int(input())
sum = 0

for i in range(1, n+1):

sum += i

print(sum)

Q26. List the different types of conditional control statements and explain them with suitable examples.
(8 Marks)

Types of Conditional Control Statements in Python

1. Simple if

a = 10

if a > 5:

print("a is greater than 5")

2. if–else

a=3

if a % 2 == 0:

print("Even")

else:

print("Odd")

3. if–elif–else

marks = 75

if marks >= 90:

print("Grade A")

elif marks >= 60:

print("Grade B")

else:

print("Grade C")

4. Nested if

a = 10

b = 20

if a > 5:

if b > 15:

print("Both conditions true")

Explanation:
Conditional statements control the flow of execution based on conditions.
**Q27.

(i) Write a python program to implement a student mark system using chained conditional if
(ii) Write a python program to find whether a number is positive, negative or zero using nested if (8 Marks)**

(i) Student Mark System

marks = int(input("Enter marks: "))

if marks >= 90:

print("Grade A")

elif marks >= 75:

print("Grade B")

elif marks >= 60:

print("Grade C")

else:

print("Fail")

(ii) Positive, Negative or Zero (Nested if)

n = int(input("Enter number: "))

if n >= 0:

if n == 0:

print("Zero")

else:

print("Positive")

else:

print("Negative")

Q28. Explain any ten string methods in Python with examples. (8 Marks)

1. upper() – Converts to uppercase

2. lower() – Converts to lowercase

3. strip() – Removes spaces

4. replace() – Replaces characters

5. split() – Splits string

6. join() – Joins elements

7. find() – Finds position


8. count() – Counts occurrences

9. startswith() – Checks starting

10. endswith() – Checks ending

Example:

s = " python "

print([Link]())

print([Link]())

**Q29.

(i) Write a Python program to check whether a string is a palindrome


(ii) Write a Python program to count the number of vowels in a string (8 Marks)**

(i) Palindrome Program

s = input("Enter string: ")

if s == s[::-1]:

print("Palindrome")

else:

print("Not Palindrome")

(ii) Count Vowels

s = input("Enter string: ")

count = 0

for ch in s:

if ch in "aeiouAEIOU":

count += 1

print("Vowels:", count)

Q30. Explain different types of operators in Python with suitable examples. (8 Marks)

Types of Operators

1. Arithmetic – + - * / %

print(10 + 5)

2. Relational – > < == !=

print(5 > 3)

3. Logical – and or not

print(True and False)


4. Bitwise – & | ^

print(5 & 3)

5. Assignment – = += -=

a=5

a += 2

6. Membership – in, not in

print('a' in 'apple')

Q31. Discuss the working of the continue and break statements in the for loop with suitable examples. (8
Marks)

Break Statement

• Immediately terminates the loop

• Control moves outside the loop

Example:

for i in range(1, 6):

if i == 4:

break

print(i)

Continue Statement

• Skips the current iteration

• Continues with the next iteration

Example:

for i in range(1, 6):

if i == 3:

continue

print(i)

Difference Between break and continue

break continue

Stops loop Skips iteration

Control exits loop Loop continues

**Q32.
(i) Write a Python program to check whether a year is a leap year
(ii) Write a Python program to check whether a number is prime or not (8 Marks)**

(i) Leap Year Program

year = int(input("Enter year: "))

if (year % 400 == 0) or (year % 4 == 0 and year % 100 != 0):

print("Leap Year")

else:

print("Not a Leap Year")

(ii) Prime Number Program

n = int(input("Enter number: "))

if n > 1:

for i in range(2, n):

if n % i == 0:

print("Not Prime")

break

else:

print("Prime")

else:

print("Not Prime")

Q33. Write a Python program using if-elif-else to check divisibility by 2, 3, and 5. (8 Marks)

n = int(input("Enter number: "))

if n % 2 == 0 and n % 3 == 0 and n % 5 == 0:

print("Divisible by 2, 3 and 5")

elif n % 2 == 0:

print("Divisible by 2")

elif n % 3 == 0:

print("Divisible by 3")

elif n % 5 == 0:

print("Divisible by 5")
else:

print("Not divisible by 2, 3 or 5")

**Q34.

(i) Write a Python program to reverse a string


(ii) Write a Python program to find frequency of each character in a string (8 Marks)**

(i) Reverse String

s = input("Enter string: ")

print("Reversed string:", s[::-1])

(ii) Frequency of Characters

s = input("Enter string: ")

freq = {}

for ch in s:

freq[ch] = [Link](ch, 0) + 1

print(freq)

Q35. Explain join(), split(), strip(), replace(), lower(), and upper() string methods with examples. (8 Marks)

Method Use Example

join() Join elements ' '.join(['a','b'])

split() Split string "a b".split()

strip() Remove spaces " hi ".strip()

replace() Replace text "hi".replace('h','H')

lower() Lowercase "HI".lower()

upper() Uppercase "hi".upper()

Q36. Write a Python program that finds sum of all numbers in a list until it encounters a negative number
using break statement. (8 Marks)

Program

numbers = [5, 10, 3, 8, -2, 7]

total = 0
for num in numbers:

if num < 0:

break

total += num

print("Sum =", total)

Explanation

• The loop iterates through the list

• When a negative number is found, break terminates the loop

• Sum is calculated only until that point

**Q37.

(i) Write a Python program to find the square root of a number using Iterative Newton’s Method
(ii) Write a Python program to find simple interest. (8 Marks)**

(i) Square Root using Newton’s Method

n = float(input("Enter number: "))

guess = n / 2

for i in range(10):

guess = (guess + n / guess) / 2

print("Square root =", guess)

(ii) Simple Interest Program

p = float(input("Enter principal: "))

r = float(input("Enter rate: "))

t = float(input("Enter time: "))

si = (p * r * t) / 100

print("Simple Interest =", si)

**Q38.

(i) Write a Python program to calculate sum of even and odd numbers separately in a list
(ii) Write a Python program to check whether a number is positive, negative or zero. (8 Marks)**

(i) Sum of Even and Odd Numbers


lst = [1, 2, 3, 4, 5, 6]

even_sum = 0

odd_sum = 0

for num in lst:

if num % 2 == 0:

even_sum += num

else:

odd_sum += num

print("Even sum =", even_sum)

print("Odd sum =", odd_sum)

(ii) Positive, Negative or Zero

n = int(input("Enter number: "))

if n > 0:

print("Positive")

elif n < 0:

print("Negative")

else:

print("Zero")

**Q39.

(i) Write a Python program to create and display elements of list and tuple
(ii) Write a Python program to check whether a number is odd or even. (8 Marks)**

(i) List and Tuple Program

lst = [10, 20, 30]

tup = (40, 50, 60)

print("List:", lst)

print("Tuple:", tup)

(ii) Odd or Even Program


n = int(input("Enter number: "))

if n % 2 == 0:

print("Even")

else:

print("Odd")

Q40. Explain the concept of recursion in Python with example. (8 Marks)

Recursion

Recursion is a programming technique where a function calls itself to solve a smaller part of the same
problem until a base condition is reached.

Example: Factorial using Recursion

def factorial(n):

if n == 0:

return 1

else:

return n * factorial(n - 1)

print(factorial(5))

Explanation

• Base case stops recursion

• Function keeps calling itself

• Result is returned step-by-step

Q41. What are the advantages of tuple over list? (2 Marks)

Advantages of tuple over list:

1. Tuples are immutable, so data cannot be changed

2. Tuples use less memory and are faster than lists

Q42. What is tuple in Python? How does it differ from list? (2 Marks)

A tuple is an ordered collection of elements enclosed in parentheses ().

Difference:

• Tuple is immutable, list is mutable

• Tuple uses (), list uses []


Q43. Illustrate ways of creating a tuple and tuple assignment with examples. (2 Marks)

Creating tuple:

t1 = (1, 2, 3)

t2 = 1, 2, 3

Tuple assignment:

a, b = (10, 20)

**Q44. Write a Python program to check whether elements ‘y’ and ‘a’ belong to the tuple

mytuple = ('p','y','t','h','o','n'). (2 Marks)**

mytuple = ('p','y','t','h','o','n')

print('y' in mytuple)

print('a' in mytuple)

Q45. Write a Python program to delete all duplicate elements in a list. (2 Marks)

lst = [1, 2, 2, 3, 4, 4]

lst = list(set(lst))

print(lst)

Q46.

(i) Write a Python program to sort ‘n’ numbers in a list using selection sort
(ii) Write a Python program to perform linear search. (8 Marks)

(i) Selection Sort Program

lst = [64, 25, 12, 22, 11]

n = len(lst)

for i in range(n):

min_index = i

for j in range(i+1, n):

if lst[j] < lst[min_index]:

min_index = j

lst[i], lst[min_index] = lst[min_index], lst[i]


print("Sorted list:", lst)

(ii) Linear Search Program

lst = [10, 20, 30, 40, 50]

key = int(input("Enter element to search: "))

for i in range(len(lst)):

if lst[i] == key:

print("Element found at position", i)

break

else:

print("Element not found")

Q47. Demonstrate the working of +, , and slice operators in Python lists and tuples. (8 Marks)

List Operators

a = [1, 2, 3]

b = [4, 5]

print(a + b) # Concatenation

print(a * 2) # Repetition

print(a[0:2]) # Slicing

Tuple Operators

t1 = (10, 20)

t2 = (30, 40)

print(t1 + t2)

print(t1 * 2)

print(t1[1:])

Q48.

(i) Write Python code to find the minimum among 10 numbers in a list
(ii) Demonstrate code to draw histogram in Python. (8 Marks)**

(i) Minimum in a List


lst = [23, 45, 12, 67, 89, 10, 34, 56, 78, 90]

min_val = lst[0]

for num in lst:

if num < min_val:

min_val = num

print("Minimum =", min_val)

(ii) Histogram Program

import [Link] as plt

data = [2, 3, 4, 5, 6, 7, 8]

[Link](data)

[Link]()

Q49. Describe the set and explain its operations with suitable examples. (8 Marks)

Set

A set is an unordered collection of unique elements enclosed in {}.

Set Operations

A = {1, 2, 3}

B = {3, 4, 5}

print(A | B) # Union

print(A & B) # Intersection

print(A - B) # Difference

Q50. Describe different functions associated with sets with suitable examples. (8 Marks)

Set Functions

s = {1, 2, 3}

[Link](4)

[Link](2)

[Link]()
[Link]()

print(s)

Explanation

• add() → adds element

• remove() → removes element

• pop() → removes random element

• clear() → empties set

Q51. Explain in detail about dictionaries and their operations with suitable examples. (8 Marks)

Dictionary

A dictionary is an unordered collection of key–value pairs, enclosed in {}.

Example

student = {

"name": "Rahul",

"age": 20,

"marks": 85

Dictionary Operations

1. Accessing values

print(student["name"])

2. Updating values

student["marks"] = 90

3. Adding new elements

student["course"] = "Python"

4. Deleting elements

del student["age"]

5. Traversing dictionary

for key, value in [Link]():

print(key, value)

**Q52.

(i) Using a dictionary, write Python code to find frequency of each character in a sentence
(ii) Write Python code to remove multiple keys from a dictionary using del. (8 Marks)**
(i) Character Frequency Program

sentence = input("Enter sentence: ")

freq = {}

for ch in sentence:

if ch in freq:

freq[ch] += 1

else:

freq[ch] = 1

print(freq)

(ii) Remove Multiple Keys

data = {"a": 1, "b": 2, "c": 3, "d": 4}

del data["b"]

del data["d"]

print(data)

Q53. What is a function? How is a function defined and called in Python? Explain with a simple program.
(8 Marks)

Function

A function is a reusable block of code that performs a specific task.

Syntax

def function_name(parameters):

statements

Example Program

def add(a, b):

return a + b

result = add(10, 20)

print("Sum =", result)

Explanation
• def keyword defines function

• Function is called using its name

• Values are passed as arguments

Q54. List the different types of arguments used in functions with suitable examples. (8 Marks)

Types of Arguments in Python

1. Positional arguments

def add(a, b):

print(a + b)

add(5, 3)

2. Keyword arguments

add(b=3, a=5)

3. Default arguments

def greet(name="User"):

print("Hello", name)

greet()

4. Variable-length arguments

def total(*n):

print(sum(n))

total(1, 2, 3)

**Q55.

Using recursion
(i) Write a Python program to find the GCD of two numbers
(ii) Write a Python program to find the exponent of a number. (8 Marks)**

(i) GCD using Recursion

def gcd(a, b):

if b == 0:

return a

else:

return gcd(b, a % b)
print(gcd(48, 18))

(ii) Exponent using Recursion

def power(a, n):

if n == 0:

return 1

else:

return a * power(a, n - 1)

print(power(2, 3))

**Q56. Describe the following:

(i) Creating the list


(ii) Accessing values in the list
(iii) Updating the list
(iv) Deleting the list elements (8 Marks)**

(i) Creating a list

A list is created using square brackets [].

lst = [10, 20, 30, 40]

(ii) Accessing values in a list

Elements are accessed using index values.

print(lst[0])

print(lst[2])

(iii) Updating the list

List elements can be modified using index.

lst[1] = 25

print(lst)

(iv) Deleting list elements

Elements can be deleted using del() or remove().

del lst[0]

[Link](30)

print(lst)
**Q57.

(i) Write a Python program using a function to generate first N Fibonacci numbers
(ii) Write a Python program to find factorial using recursion. (8 Marks)**

(i) Fibonacci using Function

def fibonacci(n):

a, b = 0, 1

for i in range(n):

print(a, end=" ")

a, b = b, a + b

fibonacci(5)

(ii) Factorial using Recursion

def factorial(n):

if n == 0:

return 1

else:

return n * factorial(n - 1)

print(factorial(5))

Q58. Define exception and describe try-except-finally block with syntax and example. (8 Marks)

Exception

An exception is an error that occurs during program execution, disrupting normal flow.

Syntax of try-except-finally

try:

statements

except:

error handling

finally:

statements
Example

try:

a = 10 / 0

except ZeroDivisionError:

print("Division by zero error")

finally:

print("Execution completed")

**Q59.

(i) Write a program to catch divide by zero exception with finally block
(ii) Write a Python program to handle multiple exceptions. (8 Marks)**

(i) Divide by Zero Exception

try:

a = int(input())

b = int(input())

print(a / b)

except ZeroDivisionError:

print("Cannot divide by zero")

finally:

print("Program ended")

(ii) Multiple Exceptions

try:

x = int(input())

y = int(input())

print(x / y)

except ZeroDivisionError:

print("Zero division error")

except ValueError:

print("Invalid input")

Q60. Mention Python list methods with examples. Why are both append() and extend() necessary? (8
Marks)

List Methods

lst = [1, 2, 3]
[Link](4)

[Link]([5, 6])

[Link](1, 10)

[Link](2)

[Link]()

[Link]()

[Link]()

append() vs extend()

• append() adds one element at the end

• extend() adds multiple elements from another list

Example:

[Link]([7, 8])

[Link]([9, 10])

Q61. What are modules in Python? How will you import them? (2 Marks)

A module is a file containing Python code such as functions, variables, and classes.

Importing a module:

import math

from math import sqrt

Q62. Explain User Defined Modules. (2 Marks)

A user-defined module is a Python file created by the user to reuse functions or variables in other programs.

Example:

import mymodule

Q63. Discuss the different modes for opening and closing a file. (2 Marks)

Common file modes:

• r – Read

• w – Write

• a – Append

• r+ – Read and write

Files are closed using:


[Link]()

Q64. Tabulate the different modes for opening a file and briefly explain them. (2 Marks)

Mode Description

r Read only

w Write (overwrites file)

a Append data

r+ Read and write

Q65. Explain the methods used to read and write into a file with examples. (2 Marks)

Reading methods: read(), readline(), readlines()


Writing method: write()

Example:

file = open("[Link]", "w")

[Link]("Hello")

[Link]()

Q66.

(i) Write a Python code to copy the contents of one file to another
(ii) Write a Python code to count the number of words in a file. (8 Marks)**

(i) Copy contents of one file to another

source = open("[Link]", "r")

destination = open("[Link]", "w")

[Link]([Link]())

[Link]()

[Link]()

Explanation:
The source file is opened in read mode and its contents are written into the destination file.

(ii) Count number of words in a file

file = open("[Link]", "r")

content = [Link]()
words = [Link]()

print("Number of words:", len(words))

[Link]()

**Q67.

(i) Write a Python code to read and print the first 20 characters in a file
(ii) Explain seek() and tell() methods. (8 Marks)**

(i) Read first 20 characters

file = open("[Link]", "r")

print([Link](20))

[Link]()

(ii) seek() and tell() methods

• seek(): Moves the file pointer to a specified position

• tell(): Returns the current position of the file pointer

Example:

file = open("[Link]", "r")

print([Link]())

[Link](5)

print([Link]())

[Link]()

Q68. Explain the role of Tkinter in Python GUI programming. Discuss its features and advantages. (8
Marks)

Tkinter

Tkinter is Python’s standard GUI (Graphical User Interface) library used to create desktop applications.

Features

• Built-in Python library

• Supports widgets like Button, Label, Entry

• Event-driven programming

• Platform independent

Advantages

• Easy to learn and use

• Lightweight and fast

• No external installation required


Q69. Provide examples of Tkinter applications such as a simple calculator, text editor, or image viewer. (8
Marks)

Example: Simple Tkinter Window

from tkinter import *

root = Tk()

[Link]("Simple App")

label = Label(root, text="Welcome to Tkinter")

[Link]()

[Link]()

Applications of Tkinter

• Calculator

• Text Editor

• Login Forms

• Image Viewer

Q70. Provide examples of using the seek() method to move the file pointer to different positions within a
file. (8 Marks)

Example Program

file = open("[Link]", "r")

[Link](0)

print([Link](10))

[Link](5)

print([Link](10))

[Link]()

Explanation

• seek(0) moves pointer to beginning

• seek(5) moves pointer to 5th character

• Allows random access of file data


Q71. Write a Python program to display the calendar of a given year and month. (8 Marks)

Program

import calendar

year = int(input("Enter year: "))

month = int(input("Enter month: "))

print([Link](year, month))

Explanation

• calendar module is used

• month() displays the calendar for the given year and month

Q72. Explain the significance of the math module in Python. Discuss the mathematical functions and
constants available. (8 Marks)

Math Module

The math module provides mathematical functions and constants for complex calculations.

Mathematical Functions

• sqrt() – Square root

• pow() – Power

• factorial() – Factorial

• ceil() – Smallest integer ≥ value

• floor() – Largest integer ≤ value

Constants

• pi – Value of π

• e – Euler’s number

Example:

import math

print([Link](16))

print([Link])

Q73. Discuss the importance of date and time functions in Python. (8 Marks)

Date and Time in Python

Python uses the datetime module to work with dates and time.
Importance

• Track current date and time

• Perform date arithmetic

• Used in logging, scheduling, and databases

Example

from datetime import datetime

now = [Link]()

print(now)

Q74. Describe the process of importing modules and packages in Python. Discuss different methods of
importing with advantages and disadvantages. (8 Marks)

Methods of Importing

1. import module

import math

✔ Simple
✖ Need module name every time

2. from module import function

from math import sqrt

✔ Direct access
✖ Name conflicts

3. import module as alias

import math as m

✔ Shorter names

Q75. Write a Python program to find minimum and maximum in a list using user-defined functions. (8
Marks)

Program

def find_min(lst):

return min(lst)

def find_max(lst):

return max(lst)

numbers = [10, 45, 23, 89, 5]


print("Minimum:", find_min(numbers))

print("Maximum:", find_max(numbers))

Explanation

User-defined functions are used to calculate minimum and maximum values.

Q76. Write a Python program for basic calculator operations. (8 Marks)

a = float(input("Enter first number: "))

b = float(input("Enter second number: "))

print("Addition:", a + b)

print("Subtraction:", a - b)

print("Multiplication:", a * b)

if b != 0:

print("Division:", a / b)

else:

print("Division by zero not allowed")

**Q77.

(i) Write a Python program to add new content to a file and display it
(ii) Write a Python program to add additional content to a file and display it. (8 Marks)**

(i) Add New Content

file = open("[Link]", "w")

[Link]("Hello Python\n")

[Link]()

file = open("[Link]", "r")

print([Link]())

[Link]()

(ii) Add Additional Content

file = open("[Link]", "a")

[Link]("File Handling\n")
[Link]()

file = open("[Link]", "r")

print([Link]())

[Link]()

Q78. Describe various file operations with examples. (8 Marks)

File Operations

• Create

• Read

• Write

• Append

• Close

Example:

file = open("[Link]", "w")

[Link]("Python")

[Link]()

Q79. Explain the general syntax for creating files with various permissions. (8 Marks)

Syntax

file = open("filename", "mode")

File Modes

• r – Read

• w – Write

• a – Append

• r+ – Read and Write

Example:

file = open("[Link]", "r")

Q80. What are Python packages? Explain with examples. (8 Marks)

Python Packages

A package is a collection of related modules.

Examples

• math
• datetime

• os

Example Code:

import os

print([Link]())

Q81. Define a class Person in Python with attributes for name and age. (2 marks)

A class in Python is a blueprint for creating objects.


The Person class can be defined with attributes name and age as follows:

class Person:

def __init__(self, name, age):

[Link] = name

[Link] = age

Q82. What is a class and object in Python? Define it with an example. (2 marks)

• A class is a blueprint that defines properties and behavior of objects.

• An object is an instance of a class.

Example:

class Student:

pass

s1 = Student()

Q83. Differentiate between instance methods, class methods, and static methods in Python. (2 marks)

• Instance method: Works with object data and uses self.

• Class method: Works with class data and uses cls.

• Static method: Does not use self or cls.

Q84. How can access specifiers (public, private, protected) be implemented in Python? (2 marks)

Python uses naming conventions to implement access specifiers:

• Public: name

• Protected: _name

• Private: __name

These control the visibility of class members.


Q85. Explain the significance of the __init__ method in Python. (2 marks)

The __init__ method is a constructor in Python.


It is automatically called when an object is created and is used to initialize object variables.

Q86. Write a Python program to create a Person class with name and age as instance variables.
Implement methods to display and update the age. (8 marks)

A class Person is created with instance variables name and age.


Methods are used to display and update the age of the person.

class Person:

def __init__(self, name, age):

[Link] = name

[Link] = age

def display(self):

print("Name:", [Link])

print("Age:", [Link])

def update_age(self, new_age):

[Link] = new_age

# Object creation

p1 = Person("Rahul", 20)

[Link]()

p1.update_age(21)

print("After updating age:")

[Link]()

Q87. Implement a Bank account system using OOPS concepts in Python. (8 marks)

A Bank class is created with attributes and methods to deposit, withdraw, and display account details.

class Bank:

def __init__(self, acc_no, holder, balance):

self.account_number = acc_no

self.account_holder = holder
self.account_balance = balance

def deposit(self, amount):

self.account_balance += amount

def withdraw(self, amount):

if amount <= self.account_balance:

self.account_balance -= amount

else:

print("Insufficient balance")

def get_account(self):

print("Account No:", self.account_number)

print("Holder:", self.account_holder)

print("Balance:", self.account_balance)

# Object creation

b1 = Bank(101, "Amit", 5000)

[Link](2000)

[Link](1000)

b1.get_account()

Q88. How can access specifiers be implemented in Python? Discuss their importance with examples. (8
marks)

Python supports access specifiers using naming conventions.

• Public → accessible everywhere

• Protected (_) → accessible within class and subclass

• Private (__) → accessible only within the class

class Sample:

def __init__(self):

self.public_var = 10

self._protected_var = 20

self.__private_var = 30
def show(self):

print(self.public_var)

print(self._protected_var)

print(self.__private_var)

obj = Sample()

[Link]()

Importance:

• Provides data security

• Controls access to variables

• Supports encapsulation

Q89. Write a class Flower with given criteria. (8 marks)

class Flower:

def __init__(self, price, color, smell):

[Link] = price

[Link] = color

[Link] = smell

def get(self):

[Link] = int(input("Enter price: "))

[Link] = input("Enter color: ")

[Link] = input("Enter smell: ")

def display(self):

print("Price:", [Link])

print("Color:", [Link])

print("Smell:", [Link])

# Objects

lilly = Flower(0, "", "")

rose = Flower(0, "", "")

hibiscus = Flower(0, "", "")


[Link]()

[Link]()

Q90. Write a Python program to create a class named ROOM and calculate area. (8 marks)

class ROOM:

def __init__(self, length, breadth):

[Link] = length

[Link] = breadth

def area(self):

return [Link] * [Link]

# Objects

study_room = ROOM(10, 12)

dining_room = ROOM(14, 16)

print("Area of Study Room:", study_room.area())

print("Area of Dining Room:", dining_room.area())

Q91. Illustrate a program to create a class named Dog with name and color as attributes demonstrating
__init__() method. (8 marks)

The __init__() method is used to initialize the attributes of a class at the time of object creation.

class Dog:

def __init__(self, name, color):

[Link] = name

[Link] = color

def display(self):

print("Dog Name:", [Link])

print("Color:", [Link])

# Object creation

d1 = Dog("Tommy", "Brown")

[Link]()
Q92. Explain how to create multiple objects to the class with programming examples. (8 marks)

A class can have multiple objects. Each object has its own copy of instance variables.

class Student:

def __init__(self, name, marks):

[Link] = name

[Link] = marks

def display(self):

print([Link], [Link])

# Multiple objects

s1 = Student("Amit", 85)

s2 = Student("Riya", 90)

s3 = Student("Karan", 78)

[Link]()

[Link]()

[Link]()

Explanation:

• One class → many objects

• Each object stores different data

• Memory is allocated separately for each object

Q93. Explain the features of Object-Oriented Programming in Python. (8 marks)

Features of OOP:

1. Encapsulation – Binding data and methods into a single unit

2. Abstraction – Hiding internal details and showing only functionality

3. Inheritance – One class acquires properties of another

4. Polymorphism – Same function name with different behavior

5. Modularity – Program divided into classes

6. Reusability – Code can be reused

7. Flexibility – Easy to modify and extend

8. Data Security – Access control using specifiers


Q94. What is a static method and how is it different from a class method? What is the purpose of the self
keyword? (8 marks)

• Static Method:

o Uses @staticmethod

o Does not access class or instance variables

• Class Method:

o Uses @classmethod

o Uses cls to access class variables

class Demo:

x = 10

@staticmethod

def static_method():

print("Static method")

@classmethod

def class_method(cls):

print(cls.x)

Purpose of self:

• Refers to current object

• Used to access instance variables and methods

Q95. Write a Python program to display information about employees in the organization using class. (8
marks)

class Employee:

def __init__(self, emp_id, name, salary):

self.emp_id = emp_id

[Link] = name

[Link] = salary

def display(self):

print("ID:", self.emp_id)

print("Name:", [Link])

print("Salary:", [Link])
# Object creation

e1 = Employee(101, "Ravi", 45000)

e2 = Employee(102, "Sita", 50000)

[Link]()

[Link]()

Q96. Write a Python program to create a Person class with name, country and date of birth. Implement a
method to determine the person's age. (8 marks)

from datetime import date

class Person:

def __init__(self, name, country, year):

[Link] = name

[Link] = country

[Link] = year

def age(self):

current_year = [Link]().year

return current_year - [Link]

p1 = Person("Rahul", "India", 2003)

print("Name:", [Link])

print("Country:", [Link])

print("Age:", [Link]())

Q97. Write a Python program to create a Calculator class. Include methods for basic arithmetic
operations. (8 marks)

class Calculator:

def add(self, a, b):

return a + b

def subtract(self, a, b):

return a - b
def multiply(self, a, b):

return a * b

def divide(self, a, b):

if b != 0:

return a / b

else:

return "Division by zero not allowed"

c = Calculator()

print("Add:", [Link](10, 5))

print("Subtract:", [Link](10, 5))

print("Multiply:", [Link](10, 5))

print("Divide:", [Link](10, 5))

Q98. Explain how you get access to the data members and member functions of the class with a sample
program. (8 marks)

Data members and member functions are accessed using the object name with dot (.) operator.

class Student:

def __init__(self, name, marks):

[Link] = name

[Link] = marks

def display(self):

print([Link], [Link])

s1 = Student("Aman", 88)

print([Link]) # Access data member

[Link]() # Access member function

Explanation:

• [Link] → data member

• [Link]() → member function


Q99. Write a Python program to display student information using class. (8 marks)

class Student:

def __init__(self, usn, name, branch):

[Link] = usn

[Link] = name

[Link] = branch

def display(self):

print("USN:", [Link])

print("Name:", [Link])

print("Branch:", [Link])

s1 = Student("25BBTCS063", "Diksha", "CSE")

[Link]()

Q100. Write a Python program to create a class representing a Circle. Include methods to calculate its
area and circumference. (8 marks)

class Circle:

def __init__(self, radius):

[Link] = radius

def area(self):

return 3.14 * [Link] * [Link]

def circumference(self):

return 2 * 3.14 * [Link]

c1 = Circle(7)

print("Area:", [Link]())

print("Circumference:", [Link]())

You might also like