Model Questions-Python Programming

2.

 




User-Defined Functions

1. Create a program with two user-defined functions: (i) one takes two numbers and returns their product; (ii) another takes a list of numbers and prints each number.

def product(a, b):

    c = a * b

    return c


def display(numbers):

    for n in numbers:

        print(n)


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

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


d = product(a, b)

print("Product =", d)


num = int(input("How many numbers do you want to enter? "))


lst = []

for i in range(num):

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

    lst.append(x)


print("The numbers are:")

display(lst)


2. Write a function to calculate the area of a rectangle.

def area(l, b):

         a= l * b

         return a

 

l = float(input("Enter length: "))

b = float(input("Enter breadth: "))

print("Area of rectangle =", area(l, b))

3. Write a function to check whether a number is even or odd.

def check(n):

    if n % 2 == 0:

        print("Even number")

    else:

        print("Odd number")

 

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

check(n)

4. Write a function to return the square and cube of a number.

def calculate(n):

    s = n * n

    c = n * n * n

    return s, c

 

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

a, b = calculate(n)

print("Square =", a)

print("Cube =", b)

5. Write a function to calculate simple interest.

def interest(p, t, r):

    si = (p * t * r) / 100

    return si

 

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

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

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

print("Simple Interest =", interest(p, t, r))

6. Calculate the area of the floor and volume of a room using two functions.

def area(l, b):

         a= l * b

         return a

 

def volume(l, b, h):

         v= l * b * h

         return v

 

l = float(input("Enter length: "))

b = float(input("Enter breadth: "))

h = float(input("Enter height: "))

print("Area of floor =", area(l, b))

print("Volume of room =", volume(l, b, h))

7. Convert length in feet into inches using a function.

def convert(f):

         a= f * 12

        return a

 

f = float(input("Enter length in feet: "))

print("Length in inches =", convert(f))

8. Input three different numbers and calculate product and average using a function.

def product(a, b, c):

         p= l * b * h

         return p

 

def average(a, b, c):

    avg = (a + b + c) / 3

    print("Average =", avg)

 

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

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

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

print("Product =", product(a, b, c))

average(a, b, c)

9. Calculate the area of a square using a function.

def area(l):

         a= l * l

         return a

 

l = float(input("Enter side length: "))

print("Area of square =", area(l))

10. Calculate the total surface area (TSA) of a cuboid using a function.

def tsa(l, b, h):

         t=2 * (l * b + b * h + h * l)

         return t

 

l = float(input("Enter length: "))

b = float(input("Enter breadth: "))

h = float(input("Enter height: "))

print("TSA of cuboid =", tsa(l, b, h))

11. Calculate the perimeter of a square using a subprogram.

def perimeter(l):

    p = 4 * l

    print("Perimeter of square =", p)

 

l = float(input("Enter side length: "))

perimeter(l)

12. Calculate the circumference of a circle using a subprogram.

def circumference(r):

    c = 2 * 3.14 * r

    print("Circumference =", c)

 

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

circumference(r)

13. Calculate the total surface area of a sphere using a subprogram.

def tsa(r):

    a = 4 * 3.14 * r * r

    print("TSA of sphere =", a)

 

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

tsa(r)

14. Calculate the curved surface area (CSA) of a cuboid.

def csa(l, b, h):

    a = 2 * h * (l + b)

    print("CSA of cuboid =", a)

 

l = float(input("Enter length: "))

b = float(input("Enter breadth: "))

h = float(input("Enter height: "))

csa(l, b, h)

15. Generate the series 2, 3, 5, 8, 13, 21, 34 up to 10 terms and calculate its sum using a subprogram.

def series():

    a = 2

    b = 3

    s = 0

    for i in range(10):

        print(a, end=" ")

        s = s + a

        c = a + b

        a = b

        b = c

    print("\nSum =", s)

 

series()

16. Find the sum of individual digits of a number using a function.

def sumdigit(n):

    s = 0

    while n > 0:

        r = n % 10

        s = s + r

        n = n // 10

    return s

 

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

print("Sum of digits =", sumdigit(n))

17. Display the multiplication table of a number using a function.

def table(n):

    for i in range(1, 11):

        print(n, "x", i, "=", n * i)

 

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

table(n)

18. Find the factorial of a number using a user-defined function.

def factorial(n):

    f = 1

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

        f = f * i

    return f

 

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

print("Factorial =", factorial(n))

19. Generate the series 2, 3, 5, 8, 13, 21, 34 up to 10 terms and display its sum using a function.

def series():

    a = 2

    b = 3

    s = 0

    for i in range(10):

        print(a, end=" ")

        s = s + a

        c=a+b

        a=b

        b=c

    print("\nSum of series =", s)

 

series()

20. Input two numbers and calculate sum, product and difference using three separate functions.

def add(a, b):

    return a + b

 

def product(a, b):

    return a * b

 

def difference(a, b):

    return a - b

 

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

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

print("Sum =", add(a, b))

print("Product =", product(a, b))

print("Difference =", difference(a, b))

21. Write a function that takes two numbers as input and returns their sum.

def add(a, b):

         a= a + b

         return a

 

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

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

print("Sum =", add(x, y))

22. Calculate the area of a circle using a function.

def area(r):

         a=3.14 * r * r

         return a

 

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

print("Area of circle =", area(r))

23. Write a function to check whether a number is prime or not.

def prime(n):

    c = 0

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

        if n % i == 0:

            c = c + 1

    if n > 1 and c == 2:

        print("Prime number")

    else:

        print("Not a prime number")

 

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

prime(n)

24. Write a function that takes a list of numbers and returns the maximum number.

def maximum(numbers):

    m = numbers[0]

    for i in numbers:

        if i > m:

            m = i

    return m

 

n = [10, 25, 5, 40, 15]

print("Maximum number =", maximum(n))

25. Write a function to check whether a number is palindrome or not.

def palindrome(n):

    temp = n

    rev = 0

    while n > 0:

        r = n % 10

        rev = rev * 10 + r

        n = n // 10

    if temp == rev:

        print("Palindrome number")

    else:

        print("Not a palindrome number")

 

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

palindrome(n)

Graphics Using Turtle

1. Write a program to move a turtle forward by 50 units.

import turtle

 

t = turtle.Turtle()

t.forward(50)

turtle.done()

2. Write a program to move a turtle backward by 50 units.

import turtle

 

t = turtle.Turtle()

t.backward(50)

turtle.done()

3. Create a turtle, check its heading, turn it right by 30 degrees, and check its heading again.

import turtle

 

t = turtle.Turtle()

print("Original heading =", t.heading())

t.right(30)

print("New heading =", t.heading())

turtle.done()

4. Create a turtle, check its heading, turn it left by 100 degrees, and check its heading again.

import turtle

 

t = turtle.Turtle()

print("Original heading =", t.heading())

t.left(100)

print("New heading =", t.heading())

turtle.done()

5. Write a program using penup() and pendown() to draw a dashed line. Move the turtle forward in steps of 30 units, alternating between drawing and not drawing.

import turtle

 

t = turtle.Turtle()

for i in range(5):

    t.pendown()

    t.forward(30)

    t.penup()

    t.forward(30)

turtle.done()

6. Write a program to draw a line using three different pen colors: move forward 50 units in black (default); change color to blue and move forward 150 units; change color to red and move forward 50 units.

import turtle

 

t = turtle.Turtle()

t.forward(50)

t.color("blue")

t.forward(150)

t.color("red")

t.forward(50)

turtle.done()

7. Write a program that asks the user for a radius and a fill color, then draws a filled circle using fillcolor(), begin_fill(), and end_fill().                                                                                                                                                                                                                                                                                                                                                                                                                                        

import turtle

 

t = turtle.Turtle()

r = int(input("Enter radius: "))

c = input("Enter fill color: ")

t.fillcolor(c)

t.begin_fill()

t.circle(r)

t.end_fill()

turtle.done()

 

Error Handling (Try-Except)

1. Write a program to read a file and handle the exception if the file does not exist.

try:

    f = open("student.txt", "r")

    print(f.read())

    f.close()

except FileNotFoundError:

    print("File does not exist.")

2. Write a program that asks the user for a numerator and denominator, divides them, and prints the result. Handle division by zero.

try:

    a = int(input("Enter numerator: "))

    b = int(input("Enter denominator: "))

    c = a / b

    print("Result =", c)

except ZeroDivisionError:

    print("Cannot divide by zero.")

3. Write a program to calculate the average of two numbers and display the result using an f-string.

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

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

result = (a + b) / 2

print(f"Average = {result}")

4. Write a program that attempts to divide a number by zero directly and observe the exception raised by Python.

try:

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

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

    c=a/b

    print(c)

except ZeroDivisionError:

    print("Error: Division by zero is not possible.")

5. Write a program using try, except, else and finally blocks to handle division by zero.

try:

    a = int(input("Enter numerator: "))

    b = int(input("Enter denominator: "))

    c = a / b

except ZeroDivisionError:

    print("Cannot divide by zero.")

else:

    print("Division successful.")

    print("Result =", c)

finally:

    print("Program completed.")

File Handling - CSV File Handling

1. Create a CSV file named students.csv and store the records of three students.

import csv

 

f = open("students.csv", "w", newline="")

w = csv.writer(f)

w.writerow(["Roll No", "Name", "Class", "Gender", "Marks", "Address"])

w.writerow([1, "Ram", 10, "M", 85, "Kathmandu"])

w.writerow([2, "Sita", 10, "F", 92, "Lalitpur"])

w.writerow([3, "Hari", 10, "M", 65, "Bhaktapur"])

f.close()

2. Read and display all the records from the existing file students.csv.

import csv

 

f = open("students.csv", "r")

r = csv.reader(f)

for row in r:

    print(row)

f.close()

3. Add (append) one more student's record to the existing file students.csv.

import csv

 

f = open("students.csv", "a", newline="")

w = csv.writer(f)

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

name = input("Enter name: ")

clas = int(input("Enter class: "))

gender = input("Enter gender: ")

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

address = input("Enter address: ")

w.writerow([roll, name, clas, gender, marks, address])

f.close()

4. Display the records of students who scored more than 80 marks.

import csv

 

f = open("students.csv", "r")

r = csv.reader(f)

next(r)

for row in r:

    if int(row[4]) > 80:

        print(row)

f.close()

5. Display the records of students whose gender is 'F'.

import csv

 

f = open("students.csv", "r")

r = csv.reader(f)

next(r)

for row in r:

    if row[3] == "F":

        print(row)

f.close()

6. Display the records of female students who scored more than 80 marks. (AND condition)

import csv

 

f = open("students.csv", "r")

r = csv.reader(f)

next(r)

for row in r:

    if row[3] == "F" and int(row[4]) > 80:

        print(row)

f.close()

7. Display the records of students who scored less than 40 marks.

import csv

 

f = open("students.csv", "r")

r = csv.reader(f)

next(r)

for row in r:

    if int(row[4]) < 40:

        print(row)

f.close()

8. Display the records of students whose marks are between 60 and 90.

import csv

 

f = open("students.csv", "r")

r = csv.reader(f)

next(r)

for row in r:

    if int(row[4]) >= 60 and int(row[4]) <= 90:

        print(row)

f.close()

9. Copy all the records from students.csv into another CSV file named students_copy.csv.

import csv

 

f = open("students.csv", "r")

r = csv.reader(f)

f2 = open("students_copy.csv", "w", newline="")

w = csv.writer(f2)

for row in r:

    w.writerow(row)

f.close()

f2.close()

10. Delete the record of a student whose Roll No is entered by the user. Save the remaining records in the same file.

import csv

 

roll = input("Enter roll number to delete: ")

f = open("students.csv", "r")

r = csv.reader(f)

data = []

for row in r:

    if row[0] != roll:

        data.append(row)

f.close()

 

f = open("students.csv", "w", newline="")

w = csv.writer(f)

w.writerows(data)

f.close()

11. Search for a student's record using Roll No. Display the record if found; otherwise, display an appropriate message.

import csv

 

roll = input("Enter roll number to search: ")

found = False

f = open("students.csv", "r")

r = csv.reader(f)

next(r)

for row in r:

    if row[0] == roll:

        print(row)

        found = True

if found == False:

    print("Record not found.")

f.close()

12. Count and display the total number of student records stored in students.csv.

import csv

 

f = open("students.csv", "r")

r = csv.reader(f)

next(r)

c = 0

for row in r:

    c = c + 1

print("Total number of students =", c)

f.close()

13. Display the student record with the highest marks.

import csv

 

f = open("students.csv", "r")

r = csv.reader(f)

next(r)

max_marks = -1

record = []

for row in r:

    if int(row[4]) > max_marks:

        max_marks = int(row[4])

        record = row

print("Student with highest marks:")

print(record)

f.close()

14. Display the student records in ascending order of marks.

import csv

 

f = open("students.csv", "r")

r = csv.reader(f)

header = next(r)

data = []

for row in r:

    data.append(row)

f.close()

 

for i in range(len(data)):

    for j in range(i + 1, len(data)):

        if int(data[i][4]) > int(data[j][4]):

            temp = data[i]

            data[i] = data[j]

            data[j] = temp

 

print(header)

for row in data:

    print(row)

15. Update the marks of a student whose Roll No is entered by the user.

import csv

 

roll = input("Enter roll number: ")

new_marks = input("Enter new marks: ")

f = open("students.csv", "r")

r = csv.reader(f)

data = []

for row in r:

    if row[0] == roll:

        row[4] = new_marks

    data.append(row)

f.close()

 

f = open("students.csv", "w", newline="")

w = csv.writer(f)

w.writerows(data)

f.close()

File Handling - Text File Handling

16. Create a text file named student.txt and store the names and classes of three students.

f = open("student.txt", "w")

f.write("Ram, 10\n")

f.write("Sita, 10\n")

f.write("Hari, 10\n")

f.close()

17. Read and display the contents of student.txt.

f = open("student.txt", "r")

data = f.read()

print(data)

f.close()

18. Add (append) another student's name and class to the existing file student.txt.

f = open("student.txt", "a")

name = input("Enter student name: ")

clas = input("Enter class: ")

f.write(name + ", " + clas + "\n")

f.close()

19. Count and display the total number of lines in student.txt.

f = open("student.txt", "r")

c = 0

for line in f:

    c = c + 1

print("Total number of lines =", c)

f.close()

20. Handle the exception if student.txt does not exist while reading the file.

try:

    f = open("student.txt", "r")

    data = f.read()

    print(data)

    f.close()

except FileNotFoundError:

    print("File does not exist.")