Saturday, November 7, 2026

Total 265 Python Program COllections SEE COMPUTER SCIENCE 2083

 

Total 265 Python Program COllections SEE COMPUTER SCIENCE 2083



CLICK HERE TO DOWNLOAD PDF FILE


4.2 User-defined Functions

Program 1: Write a Python program to input two numbers and calculate their sum using a user-defined function.

 

def add(a, b):

    return a + b

 

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

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

 

s = add(a, b)

 

print(f"Sum of {a} and {b} is {s}")

 

Program 2: Write a Python program to input two numbers and calculate their difference using a user-defined function.

 

def subtract(a, b):

    return a - b

 

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

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

 

d = subtract(a, b)

 

print(f"Difference of {a} and {b} is {d}")

 

Program 3: Write a Python program to input two numbers and calculate their product using a user-defined function.

 

def multiply(a, b):

    return a * b

 

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

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

 

p = multiply(a, b)

 

print(f"Product of {a} and {b} is {p}")

 

Program 4: Write a Python program to input two numbers and calculate their quotient using a user-defined function.

 

def divide(a, b):

    return a / b

 

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

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

 

if b != 0:

    q = divide(a, b)

    print(f"Quotient of {a} and {b} is {q}")

else:

    print("Division by zero is not allowed.")

Program 5: Write a Python program to input two numbers and calculate the average using a user-defined function.

 

def average(a, b):

    return (a + b) / 2

 

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

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

 

avg = average(a, b)

 

print(f"Average of {a} and {b} is {avg}")

 

Program 6: Write a Python program to input a number and calculate its square using a user-defined function.

 

def square(n):

    return n * n

 

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

 

s = square(n)

 

print(f"Square of {n} is {s}")

 

Program 7: Write a Python program to input a number and calculate its cube using a user-defined function.

 

def cube(n):

    return n * n * n

 

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

 

c = cube(n)

 

print(f"Cube of {n} is {c}")

 

Program 8: Write a Python program to input a number and calculate its square root using a user-defined function.

 

def square_root(n):

    return n ** 0.5

 

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

 

if n >= 0:

    sr = square_root(n)

    print(f"Square root of {n} is {sr}")

else:

    print("Square root of a negative number is not real.")

 

 

 

 

 

 

Program 9: Write a Python program to input a number and calculate its cube root using a user-defined function.

def cube_root(n):

    return n ** (1/3)

 

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

cr = cube_root(n)

print(f"Cube root of {n} is {cr}")

Program 10: Write a Python program to input two numbers and calculate their sum, difference, product, quotient, and average using a single user-defined function.

def calculate(a, b):

    s = a + b

    d = a - b

    p = a * b

    avg = (a + b) / 2

 

    if b != 0:

        q = a / b

    else:

        q = "Not possible"

 

    return s, d, p, q, avg

 

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

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

 

s, d, p, q, avg = calculate(a, b)

 

print(f"Sum of {a} and {b} is {s}")

print(f"Difference of {a} and {b} is {d}")

print(f"Product of {a} and {b} is {p}")

print(f"Quotient of {a} and {b} is {q}")

print(f"Average of {a} and {b} is {avg}")

 

Program 11: Write a Python program to input a number and calculate its square, cube, square root and cube root using a single user-defined function.

def calculate(n):

    s = n ** 2

    c = n ** 3

    sr = n ** 0.5

    cr = n ** (1/3)

 

    return s, c, sr, cr

 

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

 

s, c, sr, cr = calculate(n)

print(f"Square of {n} is {s}")

print(f"Cube of {n} is {c}")

print(f"Square root of {n} is {sr}")

print(f"Cube root of {n} is {cr}")

Program 12: Write a Python program to convert temperature from  Celsius to Fahrenheit using a user-defined function. Formula: F = (C * 9/5) + 32

 

def convert(c):

    return (c * 9/5) + 32

 

c = float(input("Enter temperature in Celsius: "))

 

f = convert(c)

 

print(f"{c}°C is equal to {f}°F")

 

Program 13: Write a Python program to convert temperature from Fahrenheit to Celsius using a user-defined function. Formula: C = (F - 32) * 5/9

 

def convert(f):

    return (f - 32) * 5/9

 

f = float(input("Enter temperature in Fahrenheit: "))

 

c = convert(f)

 

print(f"{f}°F is equal to {c}°C")

 

Program 14:  Write a Python program to convert distance from kilometres to metres using a user-defined function.

Formula: 1 km = 1000 m

 

def convert(km):

    return km * 1000

 

km = float(input("Enter distance in kilometres: "))

 

m = convert(km)

 

print(f"{km} kilometres is equal to {m} metres")

 

Program 15:  Write a Python program to convert distance from metres to kilometres using a user-defined function.

Formula: 1 km = 1000 m

 

def convert(m):

    return m / 1000

 

m = float(input("Enter distance in metres: "))

 

km = convert(m)

 

print(f"{m} metres is equal to {km} kilometres")

 

 

 

 

 

Program 16: Write a Python program to convert length from metres to centimetres using a user-defined function.

Formula: 1 m = 100 cm

 

def convert(m):

    return m * 100

 

m = float(input("Enter length in metres: "))

 

cm = convert(m)

 

print(f"{m} metres is equal to {cm} centimetres")

 

Program 17: Write a Python program to convert length from centimetres to metres using a user-defined function.

Formula: 1 m = 100 cm

 

def convert(cm):

    return cm / 100

 

cm = float(input("Enter length in centimetres: "))

 

m = convert(cm)

 

print(f"{cm} centimetres is equal to {m} metres")

 

Program 18: Write a Python program to convert weight from kilograms to grams using a user-defined function.

Formula: 1 kg = 1000 g

 

def convert(kg):

    return kg * 1000

 

kg = float(input("Enter weight in kilograms: "))

 

g = convert(kg)

 

print(f"{kg} kilograms is equal to {g} grams")

 

Program 19: Write a Python program to convert weight from grams to kilograms using a user-defined function.

Formula: 1 kg = 1000 g

 

def convert(g):

    return g / 1000

 

g = float(input("Enter weight in grams: "))

 

kg = convert(g)

 

print(f"{g} grams is equal to {kg} kilograms")

 

 

 

 

 

Program 20: Write a Python program to convert time from hours to minutes using a user-defined function.

Formula: 1 hour = 60 minutes

 

def convert(h):

    return h * 60

 

h = float(input("Enter time in hours: "))

 

m = convert(h)

 

print(f"{h} hours is equal to {m} minutes")

 

Program 21: Write a Python program to convert time from seconds to minutes using a user-defined function.

Formula: 1 minute = 60 seconds

 

def convert(s):

    return s / 60

 

s = float(input("Enter time in seconds: "))

 

m = convert(s)

 

print(f"{s} seconds is equal to {m} minutes")

 

Program 22: Write a Python program to convert time from days to hours using a user-defined function.

Formula: 1 day = 24 hours

 

def convert(d):

    return d * 24

 

d = float(input("Enter number of days: "))

 

h = convert(d)

 

print(f"{d} days is equal to {h} hours")

 

Program 23: Write a Python program to convert length from inches to centimetres using a user-defined function.

Formula: 1 inch = 2.54 cm

 

def convert(i):

    return i * 2.54

 

i = float(input("Enter length in inches: "))

 

cm = convert(i)

 

print(f"{i} inches is equal to {cm} centimetres")

 

 

 

 

Program 24: Write a Python program to convert the given number of days into years, months and remaining days using a user-defined function.

Formula: 1 year = 365 days

1 month = 30 days

 

def convert(d):

    y = d // 365

    r = d % 365

    m = r // 30

    days = r % 30

 

    return y, m, days

 

d = int(input("Enter number of days: "))

 

y, m, days = convert(d)

 

print(f"{d} days = {y} years, {m} months and {days} days")

 

 

Program 25: Write a Python program to convert time in seconds into hours, minutes and remaining seconds using a user-defined function.

Formula: 1 hour = 3600 seconds

1 minute = 60 seconds

 

def convert(s):

    h = s // 3600

    r = s % 3600

    m = r // 60

    sec = r % 60

 

    return h, m, sec

 

s = int(input("Enter time in seconds: "))

 

h, m, sec = convert(s)

 

print(f"{s} seconds = {h} hours, {m} minutes and {sec} seconds")

 

Program 26: Write a Python program to calculate simple interest using a user-defined function.

Formula: SI = (P * T * R) / 100

 

def simple_interest(p, t, r):

    return (p * t * r) / 100

 

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

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

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

 

si = simple_interest(p, t, r)

 

print(f"Simple Interest for principal {p}, time {t} years and rate {r}% is {si}")

Program 27: Write a Python program to calculate the total amount after adding simple interest to the principal using a user-defined function.

Formula: Amount = Principal + Simple Interest

 

def amount(p, si):

    return p + si

 

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

si = float(input("Enter simple interest: "))

 

print("Total Amount =", amount(p, si))

 

Program 28: Write a Python program to calculate the total amount using principal, time and rate of interest with a user-defined function.

Formula: Amount = P + (P * T * R) / 100

 

def calculate_amount(p, t, r):

    si = (p * t * r) / 100

    return p + si

 

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

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

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

 

print("Total Amount =", calculate_amount(p, t, r))

 

Program 29: Write a Python program to calculate discount amount using a user-defined function.

Formula: Discount = (Price * Discount Rate) / 100

 

def discount(price, rate):

    return (price * rate) / 100

 

price = float(input("Enter price: "))

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

 

print("Discount Amount =", discount(price, rate))

 

 

Program 30: Write a Python program to calculate selling price after discount using a user-defined function.

Formula: Selling Price = Price - Discount

 

def selling_price(price, rate):

    d = (price * rate) / 100

    return price - d

 

price = float(input("Enter price: "))

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

 

print("Selling Price =", selling_price(price, rate))

 

 

 

Program 31: Write a Python program to calculate profit using a user-defined function.

Formula: Profit = Selling Price - Cost Price

 

def profit(sp, cp):

    return sp - cp

 

cp = float(input("Enter cost price: "))

sp = float(input("Enter selling price: "))

 

print("Profit =", profit(sp, cp))

 

 

Program 32: Write a Python program to calculate loss using a user-defined function.

Formula: Loss = Cost Price - Selling Price

 

def loss(cp, sp):

    return cp - sp

 

cp = float(input("Enter cost price: "))

sp = float(input("Enter selling price: "))

 

print("Loss =", loss(cp, sp))

 

 

Program 33: Write a Python program to calculate profit percentage using a user-defined function.

Formula: Profit Percentage = (Profit / Cost Price) * 100

 

def profit_percentage(cp, sp):

    return ((sp - cp) / cp) * 100

 

cp = float(input("Enter cost price: "))

sp = float(input("Enter selling price: "))

 

print("Profit Percentage =", profit_percentage(cp, sp))

 

 

Program 34: Write a Python program to calculate loss percentage using a user-defined function.

Formula: Loss Percentage = (Loss / Cost Price) * 100

 

def loss_percentage(cp, sp):

    return ((cp - sp) / cp) * 100

 

cp = float(input("Enter cost price: "))

sp = float(input("Enter selling price: "))

 

print("Loss Percentage =", loss_percentage(cp, sp))

 

 

 

 

 

 

Program 35: Write a Python program to calculate the area of a rectangle using a user-defined function.

Formula: Area = Length * Breadth

 

def area(l, b):

    return l * b

 

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

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

 

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

 

 

Program 36: Write a Python program to calculate the perimeter of a rectangle using a user-defined function.

Formula: Perimeter = 2 * (Length + Breadth)

 

def perimeter(l, b):

    return 2 * (l + b)

 

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

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

 

print("Perimeter of rectangle =", perimeter(l, b))

 

 

Program 37: Write a Python program to calculate the area of a square using a user-defined function.

Formula: Area = Side * Side

 

def area(a):

    return a * a

 

a = float(input("Enter side: "))

 

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

 

 

Program 38: Write a Python program to calculate the perimeter of a square using a user-defined function.

Formula: Perimeter = 4 * Side

 

def perimeter(a):

    return 4 * a

 

a = float(input("Enter side: "))

 

print("Perimeter of square =", perimeter(a))

 

 

 

 

 

 

 

 

Program 39: Write a Python program to calculate the area of a circle using a user-defined function.

Formula: Area = 3.14 * Radius * Radius

 

def area(r):

    return 3.14 * r * r

 

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

 

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

 

 

Program 40: Write a Python program to calculate the circumference of a circle using a user-defined function.

Formula: Circumference = 2 * 3.14 * Radius

 

def circumference(r):

    return 2 * 3.14 * r

 

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

 

print("Circumference of circle =", circumference(r))

 

 

Program 41: Write a Python program to calculate the area of a triangle using a user-defined function.

Formula: Area = (Base * Height) / 2

 

def area(b, h):

    return (b * h) / 2

 

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

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

 

print("Area of triangle =", area(b, h))

 

 

Program 42: Write a Python program to calculate the perimeter of a triangle using a user-defined function.

Formula: Perimeter = a + b + c

 

def perimeter(a, b, c):

    return a + b + c

 

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

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

c = float(input("Enter third side: "))

 

print("Perimeter of triangle =", perimeter(a, b, c))

 

 

 

 

 

 

 

Program 43: Write a Python program to calculate the area of a triangle using Heron's formula with a user-defined function.

Formula: s = (a + b + c) / 2

Area = √(s * (s - a) * (s - b) * (s - c))

 

def area(a, b, c):

    s = (a + b + c) / 2

    return (s * (s - a) * (s - b) * (s - c)) ** 0.5

 

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

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

c = float(input("Enter third side: "))

 

print("Area of triangle =", area(a, b, c))

 

 

Program 44: Write a Python program to calculate the area of four walls of a room using a user-defined function.

Formula: Area of Four Walls = 2 * (Length + Breadth) * Height

 

def area(l, b, h):

    return 2 * (l + b) * h

 

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

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

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

 

print("Area of four walls =", area(l, b, h))

 

 

Program 45: Write a Python program to calculate the volume of a cylinder using a user-defined function.

Formula: V = 3.14 * r * r * h

 

def volume(r, h):

    return 3.14 * r * r * h

 

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

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

 

print("Volume of cylinder =", volume(r, h))

 

 

Program 46: Write a Python program to calculate the curved surface area of a cylinder using a user-defined function.

Formula: CSA = 2 * 3.14 * r * h

 

def csa(r, h):

    return 2 * 3.14 * r * h

 

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

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

 

print("Curved Surface Area of cylinder =", csa(r, h))

 

Program 47: Write a Python program to calculate the total surface area of a cylinder using a user-defined function.

Formula: TSA = 2 * 3.14 * r * (r + h)

 

def tsa(r, h):

    return 2 * 3.14 * r * (r + h)

 

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

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

 

print("Total Surface Area of cylinder =", tsa(r, h))

 

Program 48: Write a Python program to calculate the volume of a sphere using a user-defined function.

Formula: V = (4/3) * 3.14 * r * r * r

 

def volume(r):

    return (4/3) * 3.14 * r ** 3

 

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

 

print("Volume of sphere =", volume(r))

 

Program 49: Write a Python program to calculate the surface area of a sphere using a user-defined function.

Formula: SA = 4 * 3.14 * r * r

 

def surface_area(r):

    return 4 * 3.14 * r * r

 

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

 

print("Surface Area of sphere =", surface_area(r))

 

Program 50: Write a Python program to calculate the volume of a hemisphere using a user-defined function.

Formula: V = (2/3) * 3.14 * r * r * r

 

def volume(r):

    return (2/3) * 3.14 * r ** 3

 

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

 

print("Volume of hemisphere =", volume(r))

 

Program 51: Write a Python program to calculate the curved surface area of a hemisphere using a user-defined function.

Formula: CSA = 2 * 3.14 * r * r

 

def csa(r):

    return 2 * 3.14 * r * r

 

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

 

print("Curved Surface Area of hemisphere =", csa(r))

Program 52: Write a Python program to calculate the total surface area of a hemisphere using a user-defined function.

Formula: TSA = 3 * 3.14 * r * r

 

def tsa(r):

    return 3 * 3.14 * r * r

 

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

 

print("Total Surface Area of hemisphere =", tsa(r))

 

 

Program 53: Write a Python program to calculate the volume of a cuboid using a user-defined function.

Formula: V = l * b * h

 

def volume(l, b, h):

    return l * b * h

 

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

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

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

 

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

 

 

Program 54: Write a Python program to calculate the total surface area of a cuboid using a user-defined function.

Formula: TSA = 2 * (l*b + b*h + h*l)

 

def tsa(l, b, h):

    return 2 * (l*b + b*h + h*l)

 

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

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

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

 

print("Total Surface Area of cuboid =", tsa(l, b, h))

 

 

Program 55: Write a Python program to calculate the volume of a cube using a user-defined function.

Formula: V = a * a * a

 

def volume(a):

    return a ** 3

 

a = float(input("Enter side: "))

 

print("Volume of cube =", volume(a))

 

 

 

 

 

Program 56: Write a Python program to calculate the total surface area of a cube using a user-defined function.

Formula: TSA = 6 * a * a

 

def tsa(a):

    return 6 * a * a

 

a = float(input("Enter side: "))

 

print("Total Surface Area of cube =", tsa(a))

 

Program 57: Write a Python program to calculate the volume, curved surface area and total surface area of a cylinder using a single user-defined function.

Formula:

Volume = 3.14 * r * r * h, CSA = 2 * 3.14 * r * h, TSA = 2 * 3.14 * r * (r + h)

 

def calculate(r, h):

    v = 3.14 * r * r * h

    csa = 2 * 3.14 * r * h

    tsa = 2 * 3.14 * r * (r + h)

    return v, csa, tsa

 

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

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

 

v, csa, tsa = calculate(r, h)

 

print("Volume of cylinder =", v)

print("Curved Surface Area of cylinder =", csa)

print("Total Surface Area of cylinder =", tsa)

 

Program 58: Write a Python program to calculate the volume, curved surface area and total surface area of a hemisphere using a single user-defined function.

 

Formula:

Volume = (2/3) * 3.14 * r * r * r

CSA = 2 * 3.14 * r * r

TSA = 3 * 3.14 * r * r

 

def calculate(r):

    v = (2/3) * 3.14 * r ** 3

    csa = 2 * 3.14 * r * r

    tsa = 3 * 3.14 * r * r

    return v, csa, tsa

 

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

 

v, csa, tsa = calculate(r)

 

print("Volume of hemisphere =", v)

print("Curved Surface Area of hemisphere =", csa)

print("Total Surface Area of hemisphere =", tsa)

 

Program 59: Write a Python program to calculate the volume, curved surface area and total surface area of a cylinder using a single user-defined function.

Formula:

Volume = 3.14 * r * r * h

CSA = 2 * 3.14 * r * h

TSA = 2 * 3.14 * r * (r + h)

 

def calculate(r, h):

    v = 3.14 * r * r * h

    csa = 2 * 3.14 * r * h

    tsa = 2 * 3.14 * r * (r + h)

    return v, csa, tsa

 

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

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

 

v, csa, tsa = calculate(r, h)

 

print("Volume of cylinder =", v)

print("Curved Surface Area of cylinder =", csa)

print("Total Surface Area of cylinder =", tsa)

 

Program 60: Write a Python program to calculate the volume, curved surface area and total surface area of a cone using a single user-defined function.

Formula:

Volume = (1/3) * 3.14 * r * r * h

CSA = 3.14 * r * l

TSA = 3.14 * r * (r + l)

 

 

def calculate(r, h, l):

    v = (1/3) * 3.14 * r * r * h

    csa = 3.14 * r * l

    tsa = 3.14 * r * (r + l)

    return v, csa, tsa

 

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

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

l = float(input("Enter slant height: "))

 

v, csa, tsa = calculate(r, h, l)

 

print("Volume of cone =", v)

print("Curved Surface Area of cone =", csa)

print("Total Surface Area of cone =", tsa)

 

 

 

 

 

 

 

Program 61: Write a Python program to input a number and check whether it is even or odd using a user-defined function.

 

def check(n):

    if n % 2 == 0:

        return "Even"

    else:

        return "Odd"

 

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

 

print(f"{n} is an {check(n)} number.")

 

Program 62: Write a Python program to check whether a number is positive, negative or zero using a user-defined function.

 

def check(n):

    if n > 0:

        return "Positive"

    elif n < 0:

        return "Negative"

    else:

        return "Zero"

 

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

 

print(f"The number is {check(n)}.")

 

Program 63: Write a Python program to check whether a person is eligible to vote using a user-defined function.

 

def check(age):

    if age >= 18:

        return "You are eligible to vote"

    else:

        return "You are not eligible to vote"

 

age = int(input("Enter your age: "))

 

print(check(age))

 

Program 64: Write a Python program to find the greater number between two numbers using a user-defined function.

def greater(a, b):

    if a > b:

        return a

    elif b > a:

        return b

    else:

        return "Both numbers are equal"

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

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

print("Greater number =", greater(a, b))

Program 65: Write a Python program to find the smaller number between two numbers using a user-defined function.

 

def smaller(a, b):

    if a < b:

        return a

    elif b < a:

        return b

    else:

        return "Both numbers are equal"

 

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

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

 

print("Smaller number =", smaller(a, b))

 

Program 66: Write a Python program to find the greatest among three numbers using a user-defined function.

 

def greatest(a, b, c):

    if a >= b and a >= c:

        return a

    elif b >= a and b >= c:

        return b

    else:

        return c

 

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

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

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

 

print("Greatest number =", greatest(a, b, c))

 

Program 67: Write a Python program to find the middle number among three numbers using a user-defined function.

 

def middle(a, b, c):

    if (a >= b and a <= c) or (a <= b and a >= c):

        return a

    elif (b >= a and b <= c) or (b <= a and b >= c):

        return b

    else:

        return c

 

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

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

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

 

print("Middle number =", middle(a, b, c))

 

 

 

 

Program 68: Write a Python program to check whether a given year is a leap year or not using a user-defined function.

 

def leap_year(year):

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

        return "Leap year"

    else:

        return "Not a leap year"

 

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

 

print(f"{year} is a {leap_year(year)}.")

 

Program 69: Write a Python program to check whether a number is divisible by both 5 and 11 using a user-defined function.

 

def check(n):

    if n % 5 == 0 and n % 11 == 0:

        return "Divisible by both 5 and 11"

    else:

        return "Not divisible by both 5 and 11"

 

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

 

print(f"{n} is {check(n)}.")

 

Program 70: Write a Python program to check whether a student has passed or failed using a user-defined function.

 

def result(marks):

    if marks >= 40:

        return "Passed"

    else:

        return "Failed"

 

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

 

print(f"Student has {result(marks)}.")

 

Program 71: Write a Python program to check whether a person is eligible for a driving licence using a user-defined function.

 

def check(age):

    if age >= 18:

        return "Eligible for driving licence"

    else:

        return "Not eligible for driving licence"

 

age = int(input("Enter your age: "))

 

print(f"You are {check(age)}.")

 

Program 72: Write a Python program to calculate the grade of a student based on marks using a user-defined function.

 

def grade(marks):

    if marks >= 90:

        return "A+"

    elif marks >= 80:

        return "A"

    elif marks >= 70:

        return "B"

    elif marks >= 60:

        return "C"

    elif marks >= 40:

        return "D"

    else:

        return "F"

 

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

 

print(f"Your grade is {grade(marks)}.")

 

Program 73: Write a Python program to find the smallest among three numbers using a user-defined function.

 

def smallest(a, b, c):

    if a <= b and a <= c:

        return a

    elif b <= a and b <= c:

        return b

    else:

        return c

 

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

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

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

 

print("Smallest number =", smallest(a, b, c))

 

 

Program 74: Write a Python program to check whether a number is divisible by 3 or 7 using a user-defined function.

 

def check(n):

    if n % 3 == 0 or n % 7 == 0:

        return "Divisible by 3 or 7"

    else:

        return "Not divisible by 3 or 7"

 

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

 

print(check(n))

 

 

Program 75: Write a Python program to check whether three given sides can form a valid triangle using a user-defined function.

 

def check(a, b, c):

    if a > 0 and b > 0 and c > 0 and (a + b > c) and (a + c > b) and (b + c > a):

        return "Valid triangle"

    else:

        return "Invalid triangle"

 

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

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

c = float(input("Enter third side: "))

 

print(check(a, b, c))

 

Program 76: Write a Python program to calculate the electricity bill based on units consumed using a user-defined function.

 

First 20 units: Rs. 5 per unit

Next 30 units: Rs. 7 per unit

Above 50 units: Rs. 10 per unit

 

def electricity_bill(units):

    if units <= 20:

        return units * 5

    elif units <= 50:

        return (20 * 5) + (units - 20) * 7

    else:

        return (20 * 5) + (30 * 7) + (units - 50) * 10

units = float(input("Enter electricity units: "))

print("Electricity bill = Rs.", electricity_bill(units))

 

Program 77: Write a Python program to calculate the discount and final amount based on purchase amount using a user-defined function.

 

Rs. 5000 or above: 20% discount

Rs. 3000 or above: 10% discount

Rs. 1000 or above: 5% discount

Below Rs. 1000: No discount

 

def discount(amount):

    if amount >= 5000:

        return amount * 20 / 100

    elif amount >= 3000:

        return amount * 10 / 100

    elif amount >= 1000:

        return amount * 5 / 100

    else:

        return 0

amount = float(input("Enter purchase amount: "))

d = discount(amount)

print("Discount amount = Rs.", d)

print("Final amount = Rs.", amount - d)

Program 78: Write a Python program to calculate the water bill based on units consumed using a user-defined function.

 

First 10 units: Rs. 10 per unit

Next 10 units: Rs. 15 per unit

Above 20 units: Rs. 20 per unit

 

def water_bill(units):

    if units <= 10:

        return units * 10

    elif units <= 20:

        return (10 * 10) + (units - 10) * 15

    else:

        return (10 * 10) + (10 * 15) + (units - 20) * 20

 

units = float(input("Enter water units: "))

 

print("Total water bill = Rs.", water_bill(units))

 

Program 79: Write a Python program to calculate the bonus of an employee based on years of service using a user-defined function.

 

10 years or more: 20% bonus

5 years or more: 10% bonus

Below 5 years: 5% bonus

 

def bonus(salary, years):

    if years >= 10:

        return salary * 20 / 100

    elif years >= 5:

        return salary * 10 / 100

    else:

        return salary * 5 / 100

 

salary = float(input("Enter monthly salary: "))

years = int(input("Enter years of service: "))

 

b = bonus(salary, years)

 

print("Bonus amount = Rs.", b)

print("Total salary = Rs.", salary + b)

 

 

 

 

 

 

 

 

 

 

 

Program 80: Write a Python program to calculate taxi fare based on distance travelled using a user-defined function.

 

Criteria:

First 5 km: Rs. 50 per km

Next 5 km: Rs. 40 per km

Above 10 km: Rs. 30 per km

 

def taxi_fare(distance):

    if distance <= 5:

        return distance * 50

    elif distance <= 10:

        return (5 * 50) + (distance - 5) * 40

    else:

        return (5 * 50) + (5 * 40) + (distance - 10) * 30

 

distance = float(input("Enter distance travelled in km: "))

 

print("Total taxi fare = Rs.", taxi_fare(distance))

 

 

Program 81: Write a Python program to calculate the sum of digits of a number using a user-defined function.

 

def sum_digits(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 =", sum_digits(n))

 

 

Program 82: Write a Python program to count the number of digits in a given number using a user-defined function.

 

def count_digits(n):

    count = 0

    while n > 0:

        count = count + 1

        n = n // 10

    return count

 

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

 

print("Number of digits =", count_digits(n))

 

 

 

Program 83: Write a Python program to reverse a given number using a user-defined function.

 

def reverse(n):

    rev = 0

    while n > 0:

        r = n % 10

        rev = rev * 10 + r

        n = n // 10

    return rev

 

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

 

print("Reverse number =", reverse(n))

 

 

Program 84: Write a Python program to check whether a number is a palindrome or not using a user-defined function.

 

def palindrome(n):

    temp = n

    rev = 0

 

    while n > 0:

        r = n % 10

        rev = rev * 10 + r

        n = n // 10

 

    if temp == rev:

        return "Palindrome"

    else:

        return "Not Palindrome"

 

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

 

print(f"{n} is {palindrome(n)}.")

 

 

Program 85: Write a Python program to calculate the product of digits of a number using a user-defined function.

 

def product_digits(n):

    p = 1

    while n > 0:

        r = n % 10

        p = p * r

        n = n // 10

    return p

 

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

 

print("Product of digits =", product_digits(n))

 

 

Program 86: Write a Python program to calculate 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))

 

 

Program 87: Write a Python program to check whether a number is an Armstrong number or not using a user-defined function.

 

def armstrong(n):

    temp = n

    s = 0

    digits = len(str(n))

 

    while n > 0:

        r = n % 10

        s = s + r ** digits

        n = n // 10

 

    if temp == s:

        return "Armstrong number"

    else:

        return "Not an Armstrong number"

 

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

 

print(f"{n} is {armstrong(n)}.")

 

 

Program 88: Write a Python program to check whether a number is a prime number or not using a user-defined function.

 

def prime(n):

    if n <= 1:

        return "Not a prime number"

 

    for i in range(2, n):

        if n % i == 0:

            return "Not a prime number"

 

    return "Prime number"

 

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

 

print(f"{n} is a {prime(n)}.")

Program 89: Write a Python program to display the multiplication table of a given number using a user-defined function.

 

def table(n):

    for i in range(1, 11):

        print(f"{n} x {i} = {n * i}")

 

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

 

table(n)

 

Program 90: Write a Python program to calculate the sum of first n natural numbers using a user-defined function.

Formula: Sum = 1 + 2 + 3 + ... + n

 

def total(n):

    s = 0

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

        s = s + i

    return s

 

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

 

print("Sum =", total(n))

 

Program 91: Write a Python program to calculate the HCF of two numbers using a user-defined function.

 

def hcf(a, b):

    while b != 0:

        a, b = b, a % b

    return a

 

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

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

 

print("HCF =", hcf(a, b))

 

Program 92: Write a Python program to calculate the LCM of two numbers using a user-defined function.

Formula: LCM = (First Number * Second Number) / HCF

 

def lcm(a, b):

    x = a

    y = b

 

    while y != 0:

        x, y = y, x % y

 

    return (a * b) // x

 

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

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

 

print("LCM =", lcm(a, b))

Program 93: Write a Python program to display all factors of a given number using a user-defined function.

 

def factors(n):

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

        if n % i == 0:

            print(i)

 

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

 

print("Factors are:")

factors(n)

 

Program 94: Write a Python program to display the Fibonacci series up to n terms using a user-defined function.

 

def fibonacci(n):

    a = 0

    b = 1

 

    for i in range(n):

        print(a, end=" ")

        a, b = b, a + b

 

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

 

fibonacci(n)

 

Program 95: Write a Python program to check whether a number is a perfect number or not using a user-defined function.

 

def perfect(n):

    s = 0

 

    for i in range(1, n):

        if n % i == 0:

            s = s + i

 

    if s == n and n > 0:

        return "Perfect number"

    else:

        return "Not a perfect number"

 

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

 

print(f"{n} is {perfect(n)}.")

 

 

 

 

 

 

 

Program 96: Write a Python program to calculate the sum of even and odd numbers separately up to n using a user-defined function.

 

def calculate(n):

    even = 0

    odd = 0

 

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

        if i % 2 == 0:

            even = even + i

        else:

            odd = odd + i

 

    return even, odd

 

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

 

e, o = calculate(n)

 

print("Sum of even numbers =", e)

print("Sum of odd numbers =", o)

 

 

Program 97: Write a Python program to display all prime numbers up to a given number using a user-defined function.

 

def prime(n):

    for num in range(2, n + 1):

        count = 0

 

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

            if num % i == 0:

                count = count + 1

 

        if count == 2:

            print(num, end=" ")

 

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

 

print("Prime numbers are:")

prime(n)

 

 

 

 

 

 

 

 

 

 

 

Program 98: Write a Python program to calculate the monthly electricity bill based on unit consumption using a user-defined function.

Criteria:

  • 0–20 units: Rs. 30 (Minimum charge)
  • 21–45 units: Rs. 5 per unit
  • Above 45 units: Rs. 7 per unit

 

 

def electricity_bill(units):

    if units <= 20:

        bill = 30

    elif units <= 45:

        bill = units * 5

    else:

        bill = units * 7

 

    return bill

 

units = int(input("Enter the monthly unit consumption: "))

 

print("Total Electricity Bill = Rs.", electricity_bill(units))

 

 

 

Program 99: Write a Python program to calculate the delivery charge based on the distance using a user-defined function.

 

Criteria:

- Up to 5 km: Rs. 50

- Above 5 km up to 10 km: Rs. 100

- Above 10 km: Rs. 150

 

def delivery_charge(distance):

    if distance <= 5:

        charge = 50

    elif distance <= 10:

        charge = 100

    else:

        charge = 150

 

    return charge

 

distance = float(input("Enter delivery distance in km: "))

 

print("Delivery Charge = Rs.", delivery_charge(distance))

 

 

 

 

 

 

 

Program 100: Write a Python program to calculate the employee bonus based on monthly salary using a user-defined function.

 

Criteria:

- Salary Rs. 70,000 or above: 25% bonus

- Salary Rs. 50,000 or above: 20% bonus

- Salary Rs. 40,000 or above: 15% bonus

- Salary Rs. 30,000 or above: 10% bonus

- Below Rs. 30,000: 5% bonus

 

def bonus(salary):

    if salary >= 70000:

        b = salary * 25 / 100

    elif salary >= 50000:

        b = salary * 20 / 100

    elif salary >= 40000:

        b = salary * 15 / 100

    elif salary >= 30000:

        b = salary * 10 / 100

    else:

        b = salary * 5 / 100

 

    return b

 

salary = float(input("Enter monthly salary: "))

 

print("Employee Bonus = Rs.", bonus(salary))


 

Program 101: Write a Python program to calculate the square root of a number using the math module.

 

import math

 

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

 

result = math.sqrt(num)

 

print("Square Root =", result)

 

 

# Program 102: Write a Python program to calculate the power of a number using the math module.

 

import math

 

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

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

 

result = math.pow(num, power)

 

print("Result =", result)

 

 

# Program 103: Write a Python program to calculate the area of a circle using the math module.

 

import math

 

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

 

area = math.pi * radius * radius

 

print("Area of Circle =", area)

 

 

# Program 104: Write a Python program to round a decimal number upward using the ceil() function.

 

import math

 

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

 

print("Ceiling Value =", math.ceil(num))

 

 

# Program 105: Write a Python program to round a decimal number downward using the floor() function.

 

import math

 

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

 

print("Floor Value =", math.floor(num))

 

 

# Program 106: Write a Python program to calculate the factorial of a number using the math module.

 

import math

 

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

 

result = math.factorial(num)

 

print("Factorial =", result)

 

 

# Program 107: Write a Python program to calculate the circumference of a circle using the math module.

 

import math

 

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

 

circumference = 2 * math.pi * radius

 

print("Circumference =", circumference)

 

 

# Program 108: Write a Python program to calculate the base-10 logarithm of a number using the math module.

 

import math

 

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

 

print("Logarithm =", math.log10(num))

 

 

# Program 109: Write a Python program to calculate the sine, cosine and tangent of an angle using the math module.

 

import math

 

angle = float(input("Enter angle in degrees: "))

 

radian = math.radians(angle)

 

print("Sine =", math.sin(radian))

print("Cosine =", math.cos(radian))

print("Tangent =", math.tan(radian))

 

 

# Program 110: Write a Python program to find the GCD (Greatest Common Divisor) of two numbers using the math module.

 

import math

 

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

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

result = math.gcd(a, b)

print("GCD =", result)

 

# Program 111: Write a Python program to find the LCM of three numbers using the math module.

 

import math

 

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

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

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

 

result = math.lcm(a, b, c)

 

print("LCM =", result)

 

 

# Program 112: Write a Python program to find the absolute value of a number using the math module.

 

import math

 

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

 

print("Absolute Value =", math.fabs(num))

 

 

# Program 113: Write a Python program to find the remainder when one number is divided by another using the math module.

 

import math

 

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

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

 

print("Remainder =", math.fmod(a, b))

 

 

# Program 114: Write a Python program to calculate the cube root of a number using the math module.

 

import math

 

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

 

print("Cube Root =", math.cbrt(num))

 

 

Program 115: Write a Python program to generate a random integer between 1 and 100 using the random module.

 

import random

 

num = random.randint(1, 100)

 

print("Random Number =", num)

 

 

 

# Program 116: Write a Python program to generate a random number between 1 and 50 using randrange().

 

import random

 

num = random.randrange(1, 51)

 

print("Random Number =", num)

 

 

# Program 117: Write a Python program to select a random fruit from a list using the random module.

 

import random

 

fruits = ["Apple", "Banana", "Mango", "Orange", "Grapes"]

 

print("Selected Fruit =", random.choice(fruits))

 

 

# Program 118: Write a Python program to select a random character from a string.

 

import random

 

word = input("Enter a word: ")

 

print("Random Character =", random.choice(word))

 

 

# Program 119: Write a Python program to generate a random floating-point number between 0 and 1.

 

import random

 

num = random.random()

 

print("Random Number =", num)

 

# Program 120: Write a Python program to shuffle the elements of a list randomly.

 

import random

 

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

 

random.shuffle(numbers)

 

print("Shuffled List =", numbers)

 

# Program 121: Write a Python program to simulate rolling a dice using the random module.

 

import random

 

dice = random.randint(1, 6)

 

print("Dice Result =", dice)

# Program 122: Write a Python program to generate a random OTP of four digits.

 

import random

 

otp = random.randint(1000, 9999)

 

print("Your OTP is:", otp)

 

# Program 123: Write a Python program to display the current date using the datetime module.

 

import datetime

 

today = datetime.date.today()

 

print("Current Date =", today)

 

# Program 124: Write a Python program to display the current date and time.

 

import datetime

 

now = datetime.datetime.now()

 

print("Current Date and Time =", now)

 

# Program 125: Write a Python program to display the current year, month and day separately.

 

import datetime

 

today = datetime.date.today()

 

print("Year =", today.year)

print("Month =", today.month)

print("Day =", today.day)

 

# Program 126: Write a Python program to display the current hour, minute and second.

 

import datetime

 

now = datetime.datetime.now()

 

print("Hour =", now.hour)

print("Minute =", now.minute)

print("Second =", now.second)

 

# Program 127: Write a Python program to display the current date in DD-MM-YYYY format.

 

import datetime

 

today = datetime.date.today()

 

print("Date =", today.strftime("%d-%m-%Y"))

 

# Program 128: Write a Python program to display the current day name and month name.

 

import datetime

 

today = datetime.datetime.now()

 

print("Day =", today.strftime("%A"))

print("Month =", today.strftime("%B"))

 

# Program 129: Write a Python program to check whether a given year is a leap year.

 

import calendar

 

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

 

if calendar.isleap(year):

    print(year, "is a Leap Year")

else:

    print(year, "is not a Leap Year")

 

# Program 130: Write a Python program to calculate the age of a person in years using the datetime module.

 

 

import datetime

 

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

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

birth_day = int(input("Enter birth day: "))

 

birth_date = datetime.date(birth_year, birth_month, birth_day)

today = datetime.date.today()

 

age = today.year - birth_date.year

 

if (today.month, today.day) < (birth_date.month, birth_date.day):

    age = age - 1

 

print("Your Age =", age, "years")

 


 

# Program 131: Write a Python program to draw a straight line using the turtle module.

 

import turtle

 

t = turtle.Turtle()

 

t.forward(150)

 

turtle.done()

 

 

# Program 132: Write a Python program to draw a square using the turtle module.

 

import turtle

 

t = turtle.Turtle()

 

for i in range(4):

    t.forward(100)

    t.right(90)

 

turtle.done()

 

 

# Program 133: Write a Python program to draw a rectangle using the turtle module.

 

import turtle

 

t = turtle.Turtle()

 

for i in range(2):

    t.forward(150)

    t.right(90)

    t.forward(80)

    t.right(90)

 

turtle.done()

 

 

# Program 134: Write a Python program to draw a triangle using the turtle module.

 

import turtle

 

t = turtle.Turtle()

 

for i in range(3):

    t.forward(100)

    t.right(120)

 

turtle.done()

 

 

# Program 135: Write a Python program to draw a circle using the turtle module.

 

import turtle

 

t = turtle.Turtle()

 

t.circle(80)

 

turtle.done()

 

 

# Program 136: Write a Python program to draw a pentagon using the turtle module.

 

import turtle

 

t = turtle.Turtle()

 

for i in range(5):

    t.forward(100)

    t.right(72)

 

turtle.done()

 

 

# Program 137: Write a Python program to draw a hexagon using the turtle module.

 

import turtle

 

t = turtle.Turtle()

 

for i in range(6):

    t.forward(100)

    t.right(60)

 

turtle.done()

 

 

# Program 138: Write a Python program to draw a star using the turtle module.

 

import turtle

 

t = turtle.Turtle()

 

for i in range(5):

    t.forward(150)

    t.right(144)

 

turtle.done()

 

 

 

 

# Program 139: Write a Python program to draw a coloured square using the turtle module.

 

import turtle

 

t = turtle.Turtle()

 

t.color("blue")

t.fillcolor("yellow")

 

t.begin_fill()

 

for i in range(4):

    t.forward(100)

    t.right(90)

 

t.end_fill()

 

turtle.done()

 

# Program 140: Write a Python program to draw a spiral pattern using the turtle module.

 

import turtle

 

t = turtle.Turtle()

 

for i in range(50):

    t.forward(i * 5)

    t.right(90)

 

turtle.done()

 

# Program 141: Write a Python program to draw a square using a user-defined function.

 

import turtle

 

t = turtle.Turtle()

 

def square():

    for i in range(4):

        t.forward(100)

        t.right(90)

 

square()

 

turtle.done()

 

 

 

 

 

 

 

# Program 142: Write a Python program to draw a triangle using a user-defined function.

 

import turtle

 

t = turtle.Turtle()

 

def triangle():

    for i in range(3):

        t.forward(100)

        t.left(120)

 

triangle()

 

turtle.done()

 

 

# Program 143: Write a Python program to draw a rectangle using a user-defined function.

 

import turtle

 

t = turtle.Turtle()

 

def rectangle():

    for i in range(2):

        t.forward(150)

        t.left(90)

        t.forward(80)

        t.left(90)

 

rectangle()

 

turtle.done()

 

 

# Program 144: Write a Python program to draw a flower using a user-defined function.

 

import turtle

 

t = turtle.Turtle()

 

def flower():

    for i in range(6):

        t.circle(50)

        t.right(60)

 

flower()

 

turtle.done()

 

 

 

 

# Program 145: Write a Python program to draw a colourful square using a user-defined function.

 

import turtle

 

t = turtle.Turtle()

 

def square():

    t.fillcolor("yellow")

    t.begin_fill()

 

    for i in range(4):

        t.forward(100)

        t.right(90)

 

    t.end_fill()

 

t.color("blue")

square()

 

turtle.done()

 

 

# Program 146: Write a Python program to handle ZeroDivisionError using try-except.

 

try:

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

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

 

    result = a / b

 

    print("Division =", result)

 

except ZeroDivisionError:

    print("Error: Cannot divide by zero.")

 

 

# Program 147: Write a Python program to handle ValueError while entering a number.

 

try:

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

 

    print("Number =", num)

 

except ValueError:

    print("Error: Please enter a valid integer.")

 

 

 

 

 

 

 

# Program 148: Write a Python program to handle multiple exceptions using try-except.

 

try:

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

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

 

    result = a / b

 

    print("Result =", result)

 

except ValueError:

    print("Error: Please enter valid numbers.")

 

except ZeroDivisionError:

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

 

 

# Program 149: Write a Python program to handle IndexError using try-except.

 

try:

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

 

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

 

    print("Value =", numbers[index])

 

except IndexError:

    print("Error: Invalid list index.")

 

except ValueError:

    print("Error: Please enter an integer.")

 

 

# Program 150: Write a Python program to handle TypeError using try-except.

 

try:

    a = 10

    b = "20"

 

    result = a + b

 

    print("Result =", result)

 

except TypeError:

    print("Error: Cannot add an integer and a string.")

 

 

 

 

 

 

 

# Program 151: Write a Python program to handle FileNotFoundError using try-except.

 

try:

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

 

    print(file.read())

 

    file.close()

 

except FileNotFoundError:

    print("Error: File not found.")

 

 

# Program 152: Write a Python program to use try-except-else blocks.

 

try:

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

 

except ValueError:

    print("Error: Invalid input.")

 

else:

    print("You entered:", num)

 

# Program 153: Write a Python program to use try-except-finally blocks.

 

try:

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

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

 

    print("Division =", a / b)

 

except ZeroDivisionError:

    print("Error: Cannot divide by zero.")

 

except ValueError:

    print("Error: Enter valid numbers.")

 

finally:

    print("Program execution completed.")

 

# Program 154: Write a Python program to raise an exception if age is below 18.

 

try:

    age = int(input("Enter your age: "))

 

    if age < 18:

        raise ValueError("Age must be 18 or above.")

 

    print("You are eligible.")

except ValueError as e:

    print("Error:", e)

# Program 155: Write a Python program to handle division and display the result only when valid.

try:

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

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

 

    result = a / b

 

except (ValueError, ZeroDivisionError) as e:

    print("Error:", e)

 

else:

    print("Division Result =", result)

 

finally:

    print("Thank you for using the program.")

 

# Program 156:: Write a Python program to create a simple calculator that performs addition, subtraction, multiplication and division using try-except blocks to handle errors.

try:

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

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

 

    print("1. Addition")

    print("2. Subtraction")

    print("3. Multiplication")

    print("4. Division")

 

    choice = int(input("Enter your choice (1-4): "))

 

    if choice == 1:

        print("Result =", a + b)

 

    elif choice == 2:

        print("Result =", a - b)

 

    elif choice == 3:

        print("Result =", a * b)

 

    elif choice == 4:

        print("Result =", a / b)

 

    else:

        print("Invalid choice!")

 

except ValueError:

    print("Error: Please enter valid numbers.")

 

except ZeroDivisionError:

    print("Error: Cannot divide by zero.")

 

finally:

    print("Thank you for using the calculator.")

# Program 157:  Write a Python program to develop a number guessing game. The computer should generate a random number between 1 and 100. The user should continue guessing until the correct number is entered. Use a while loop and try-except blocks to handle invalid input.

 

import random

 

number = random.randint(1, 100)

attempts = 0

 

while True:

    try:

        guess = int(input("Guess a number (1-100): "))

 

        attempts = attempts + 1

 

        if guess < 1 or guess > 100:

            print("Enter a number between 1 and 100.")

 

        elif guess < number:

            print("Too low! Try again.")

 

        elif guess > number:

            print("Too high! Try again.")

 

        else:

            print("Congratulations! Correct Guess.")

            print("Total Attempts =", attempts)

            break

 

    except ValueError:

        print("Invalid input! Enter an integer.")

 

# Program 158:  Write a Python program to calculate the total marks, percentage and grade of a student in five subjects. Use a while loop to accept marks and try-except blocks to handle invalid entries.

Criteria:

  • 80% and above: A
  • 60% and above: B
  • 40% and above: C
  • Below 40%: Fail

 

total = 0

count = 1

 

while count <= 5:

    try:

        marks = float(input("Enter marks of subject " + str(count) + ": "))

 

        if marks < 0 or marks > 100:

            print("Marks must be between 0 and 100.")

            continue

 

        total = total + marks

        count = count + 1

 

    except ValueError:

        print("Invalid input! Enter numeric marks.")

 

percentage = total / 5

 

print("Total Marks =", total)

print("Percentage =", percentage, "%")

 

if percentage >= 80:

    print("Grade = A")

 

elif percentage >= 60:

    print("Grade = B")

 

elif percentage >= 40:

    print("Grade = C")

 

else:

    print("Grade = Fail")

 

# Program 159: Write a Python program to develop a menu-driven mathematical calculator using a while loop, user-defined functions, the math module and exception handling. The calculator should perform square root, factorial, power, GCD and LCM operations until the user chooses to exit.

 

 

import math

 

def calculator():

    while True:

        print("\n--- MATHEMATICAL CALCULATOR ---")

        print("1. Square Root")

        print("2. Factorial")

        print("3. Power")

        print("4. GCD")

        print("5. LCM")

        print("6. Exit")

 

        try:

            choice = int(input("Enter your choice: "))

 

            if choice == 1:

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

 

                if n < 0:

                    print("Negative number not allowed.")

                else:

                    print("Square Root =", math.sqrt(n))

 

            elif choice == 2:

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

 

                if n < 0:

                    print("Negative number not allowed.")

                else:

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

 

            elif choice == 3:

                a = float(input("Enter base: "))

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

 

                print("Result =", math.pow(a, b))

 

            elif choice == 4:

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

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

 

                print("GCD =", math.gcd(a, b))

 

            elif choice == 5:

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

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

 

                print("LCM =", math.lcm(a, b))

 

            elif choice == 6:

                print("Thank you for using calculator.")

                break

 

            else:

                print("Invalid choice!")

 

        except ValueError:

            print("Invalid input! Please enter valid numbers.")

 

calculator()

 

# Program 160: Write a Python program to develop a simple bank account management system. The program should allow users to deposit money, withdraw money, check balance and exit. Use a while loop, user-defined functions and try-except blocks to handle invalid input.

 

 

balance = 1000

 

def deposit():

    global balance

 

    amount = float(input("Enter deposit amount: "))

 

    if amount <= 0:

        print("Enter a positive amount.")

    else:

        balance = balance + amount

        print("Deposit successful.")

        print("Current Balance =", balance)

 

 

def withdraw():

    global balance

 

    amount = float(input("Enter withdrawal amount: "))

 

    if amount <= 0:

        print("Enter a positive amount.")

 

    elif amount > balance:

        print("Insufficient balance.")

 

    else:

        balance = balance - amount

        print("Withdrawal successful.")

        print("Current Balance =", balance)

 

 

while True:

    print("\n--- BANK MANAGEMENT SYSTEM ---")

    print("1. Deposit")

    print("2. Withdraw")

    print("3. Check Balance")

    print("4. Exit")

 

    try:

        choice = int(input("Enter your choice: "))

 

        if choice == 1:

            deposit()

 

        elif choice == 2:

            withdraw()

 

        elif choice == 3:

            print("Current Balance =", balance)

 

        elif choice == 4:

            print("Thank you for banking with us.")

            break

 

        else:

            print("Invalid choice!")

 

    except ValueError:

        print("Invalid input! Please enter a valid number.")

 

 

 

 

# Program 161: Write a Python program to create a file and write text into it.

 

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

 

file.write("Welcome to Python Programming.")

 

file.close()

 

print("Data written successfully.")

 

 

# Program 162: Write a Python program to read and display the contents of a file.

 

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

 

data = file.read()

 

print("File Content:")

print(data)

 

file.close()

 

 

# Program 163: Write a Python program to append new content to an existing file.

 

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

 

file.write("\nPython is an easy programming language.")

 

file.close()

 

print("Data appended successfully.")

 

# Program 164: Write a Python program to read a file line by line.

 

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

 

for line in file:

    print(line, end="")

 

file.close()

 

# Program 165: Write a Python program to count the number of characters in a file.

 

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

 

data = file.read()

 

print("Total Characters =", len(data))

 

file.close()

# Program 166: Write a Python program to count the number of words in a file.

 

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

 

data = file.read()

 

words = data.split()

 

print("Total Words =", len(words))

 

file.close()

 

 

# Program 167: Write a Python program to count the number of lines in a file.

 

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

 

lines = file.readlines()

 

print("Total Lines =", len(lines))

 

file.close()

 

 

# Program 168: Write a Python program to create a file using exclusive creation mode.

 

try:

    file = open("newfile.txt", "x")

 

    file.write("This is a newly created file.")

 

    file.close()

 

    print("File created successfully.")

 

except FileExistsError:

    print("Error: File already exists.")

 

 

# Program 169: Write a Python program to check whether a file exists and read its contents.

 

try:

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

 

    print(file.read())

 

    file.close()

 

except FileNotFoundError:

    print("Error: File does not exist.")

 

 

# Program 170: Write a Python program to write multiple lines into a file using writelines().

 

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

 

lines = [

    "Python Programming\n",

    "File Handling\n",

    "Computer Science\n"

]

 

file.writelines(lines)

 

file.close()

 

print("Multiple lines written successfully.")

 

# Program 171: Write a Python program to read and display the first line of a file using readline().

 

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

 

line = file.readline()

 

print("First Line =", line)

 

file.close()

 

 

# Program 172: Write a Python program to read and display the first 10 characters of a file using read(10).

 

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

 

data = file.read(10)

 

print("First 10 Characters =", data)

 

file.close()

 

 

# Program 173: Write a Python program to write multiple lines into a file using write() and with open().

 

with open("file.txt", "w") as file:

    file.write("This is the first line.\n")

    file.write("This is the second line.\n")

    file.write("This is the third line.")

 

print("Data written successfully.")

 

 

 

 

 

 

# Program 174: Write a Python program to write and read data using w+ file handling mode.

 

file = open("student.txt", "w+")

 

file.write("Welcome to Python Programming.")

 

file.seek(0)

 

data = file.read()

 

print("File Content =", data)

 

file.close()

 

 

# Program 175: Write a Python program to append text to an existing file using append mode.

 

file = open("geek.txt", "a")

 

file.write("\nPython programming is fun.")

 

file.close()

 

print("Data appended successfully.")

 

# Program 176: Write a Python program to create and write data into a file using with open().

 

with open("student.txt", "w") as file:

    file.write("Welcome to Computer Science.\n")

    file.write("Learning Python Programming.")

 

print("File created and data written successfully.")

 

 

# Program 177: Write a Python program to read the contents of a file using with open().

 

with open("student.txt", "r") as file:

    data = file.read()

 

print("File Content:")

print(data)

 

 

# Program 178: Write a Python program to append new data to a file using with open().

 

with open("student.txt", "a") as file:

    file.write("\nFile handling is an important Python concept.")

 

print("Data appended successfully.")

 

 

 

# Program 179: Write a Python program to count the number of words in a file using with open().

 

with open("student.txt", "r") as file:

    data = file.read()

 

words = data.split()

 

print("Total Words =", len(words))

 

# Program 180: Write a Python program to handle file errors using with open() and try-except.

 

try:

    with open("student.txt", "r") as file:

        data = file.read()

 

    print("File Content:")

    print(data)

 

except FileNotFoundError:

    print("Error: File does not exist.")

 

print("Program completed.")

 

# Program 181: Write a Python program to read a file using try-except-else-finally blocks.

 

try:

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

    data = file.read()

 

except FileNotFoundError:

    print("Error: File not found.")

 

else:

    print("File Content:")

    print(data)

 

finally:

    print("File reading operation completed.")

 

# Program 182: Write a Python program to write data into a file using try-except-else-finally blocks.

try:

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

    file.write("Welcome to Python File Handling.")

 

except OSError:

    print("Error: Unable to write into the file.")

 

else:

    print("Data written successfully.")

 

finally:

    print("Writing operation completed.")

# Program 183: Write a Python program to append data into a file using try-except-else-finally blocks.

 

try:

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

    file.write("\nPython is easy to learn.")

 

except OSError:

    print("Error: Unable to append data.")

 

else:

    print("Data appended successfully.")

 

finally:

    print("Appending operation completed.")

 

# Program 184: Write a Python program to copy the contents of one file into another file using exception handling.

 

try:

    with open("source.txt", "r") as source:

        data = source.read()

 

    with open("destination.txt", "w") as destination:

        destination.write(data)

 

except FileNotFoundError:

    print("Error: Source file not found.")

 

except OSError:

    print("Error: File operation failed.")

 

else:

    print("File copied successfully.")

 

finally:

    print("Copy operation completed.")

 

# Program 185: Write a Python program to count the number of words in a file using try-except-else-finally blocks.

 

try:

    with open("student.txt", "r") as file:

        data = file.read()

 

except FileNotFoundError:

    print("Error: File not found.")

 

else:

    words = data.split()

    print("Total Words =", len(words))

 

finally:

    print("Word counting operation completed.")

 

# Program 186: Write a Python program to read and display all records from a CSV file using csv.reader().

 

import csv

 

with open("students.csv", "r", newline="") as file:

    reader = csv.reader(file)

 

    for row in reader:

        print(row)

 

# Program 187: Write a Python program to create a CSV file and write a single row using writerow().

 

import csv

 

with open("students.csv", "w", newline="") as file:

    writer = csv.writer(file)

 

    writer.writerow(["Name", "Age", "Marks"])

    writer.writerow(["Ram", 16, 85])

 

print("Data written successfully.")

 

# Program 188: Write a Python program to write multiple records into a CSV file using writerows().

 

import csv

 

data = [

    ["Name", "Age", "Marks"],

    ["Ram", 16, 85],

    ["Sita", 15, 92],

    ["Hari", 17, 78],

    ["Gita", 16, 88]

]

 

with open("students.csv", "w", newline="") as file:

    writer = csv.writer(file)

 

    writer.writerows(data)

 

print("Multiple records written successfully.")

 

# Program 189: Write a Python program to append a new record to an existing CSV file.

 

import csv

 

with open("students.csv", "a", newline="") as file:

    writer = csv.writer(file)

 

    writer.writerow(["Mina", 16, 90])

 

print("New record appended successfully.")

 

# Program 190: Write a Python program to read and display records from a CSV file without displaying the header.

import csv

 

with open("students.csv", "r", newline="") as file:

    reader = csv.reader(file)

 

    next(reader)

 

    for row in reader:

        print(row)

 

# Program 191: Write a Python program to display only the names of students from a CSV file.

 

import csv

 

with open("students.csv", "r", newline="") as file:

    reader = csv.reader(file)

 

    next(reader)

 

    for row in reader:

        print("Student Name =", row[0])

 

# Program 192: Write a Python program to count the total number of student records in a CSV file.

import csv

 

count = 0

 

with open("students.csv", "r", newline="") as file:

    reader = csv.reader(file)

 

    next(reader)

 

    for row in reader:

        count = count + 1

 

print("Total Students =", count)

 

# Program 193: Write a Python program to search for a student's name in a CSV file.

import csv

 

name = input("Enter student name to search: ")

found = False

 

with open("students.csv", "r", newline="") as file:

    reader = csv.reader(file)

 

    next(reader)

    for row in reader:

        if row[0].lower() == name.lower():

            print("Record Found:", row)

            found = True

            break

 

if found == False:

    print("Student record not found.")

 

# Program 194: Write a Python program to calculate the total and average marks of students from a CSV file.

import csv

 

total = 0

count = 0

 

with open("students.csv", "r", newline="") as file:

    reader = csv.reader(file)

 

    next(reader)

 

    for row in reader:

        total = total + int(row[2])

        count = count + 1

 

if count > 0:

    average = total / count

 

    print("Total Marks =", total)

    print("Average Marks =", average)

 

else:

    print("No student records found.")

 

# Program 195: Write a Python program to read a CSV file and handle errors using try-except-else-finally.

import csv

 

try:

    with open("students.csv", "r", newline="") as file:

        reader = csv.reader(file)

 

        for row in reader:

            print(row)

 

except FileNotFoundError:

    print("Error: CSV file not found.")

 

except csv.Error:

    print("Error: Unable to read CSV data.")

 

else:

    print("CSV file read successfully.")

finally:

    print("File reading operation completed.")

 

 

 

# Program 196: Write a Python program to create a Student Record Management System using CSV file handling and a while loop.

 

import csv

 

filename = "students.csv"

 

# Create the CSV file with a header if it does not exist.

try:

    with open(filename, "x", newline="") as file:

        writer = csv.writer(file)

        writer.writerow(["Name", "Age", "Marks"])

 

except FileExistsError:

    pass

 

 

while True:

    print("\n--- STUDENT RECORD MANAGEMENT SYSTEM ---")

    print("1. Add Student Record")

    print("2. Display All Records")

    print("3. Search Student")

    print("4. Exit")

 

    try:

        choice = int(input("Enter your choice: "))

 

        if choice == 1:

            name = input("Enter student name: ")

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

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

 

            if age <= 0 or marks < 0 or marks > 100:

                print("Invalid age or marks.")

 

            else:

                with open(filename, "a", newline="") as file:

                    writer = csv.writer(file)

                    writer.writerow([name, age, marks])

 

                print("Student record added successfully.")

 

        elif choice == 2:

            with open(filename, "r", newline="") as file:

                reader = csv.reader(file)

 

                for row in reader:

                    print(row)

 

        elif choice == 3:

            name = input("Enter student name: ")

            found = False

 

            with open(filename, "r", newline="") as file:

                reader = csv.reader(file)

 

                next(reader)

 

                for row in reader:

                    if row[0].lower() == name.lower():

                        print("Student Record =", row)

                        found = True

                        break

 

            if not found:

                print("Student record not found.")

 

        elif choice == 4:

            print("Thank you for using the system.")

            break

 

        else:

            print("Invalid choice. Please select 1 to 4.")

 

    except ValueError:

        print("Error: Please enter valid numeric values.")

 

    except FileNotFoundError:

        print("Error: Student file not found.")

 

    except OSError:

        print("Error: File operation failed.")

 


 

 

# Program 197: Write a Python program to read and display the contents of a CSV file using the Pandas library.

 

import pandas as pd

 

data = pd.read_csv("Salary_Data.csv")

 

print(data)

 

# Program 198: Write a Python program to display the column names of a CSV file using Pandas.

 

import pandas as pd

 

data = pd.read_csv("Salary_Data.csv")

 

print("Column Names:")

print(data.columns)

 

# Program 199: Write a Python program to display a particular column from a CSV file using Pandas.

 

import pandas as pd

 

data = pd.read_csv("Salary_Data.csv")

 

print("Salary Details:")

print(data["Salary"])

 

# Program 200: Write a Python program to display the first five records of a CSV file using Pandas.

 

import pandas as pd

 

data = pd.read_csv("Salary_Data.csv")

 

print(data.head())

 

# Program 201: Write a Python program to display the last five records of a CSV file using Pandas.

 

import pandas as pd

 

data = pd.read_csv("Salary_Data.csv")

 

print(data.tail())

 

 

# Program 202: Write a Python program to display the number of rows and columns in a CSV file using Pandas.

 

import pandas as pd

 

data = pd.read_csv("Salary_Data.csv")

 

print("Number of Rows =", data.shape[0])

print("Number of Columns =", data.shape[1])

# Program 203: Write a Python program to display information about a DataFrame using Pandas.

 

import pandas as pd

 

data = pd.read_csv("Salary_Data.csv")

 

data.info()

 

# Program 204: Write a Python program to display statistical information about a CSV file using Pandas.

 

import pandas as pd

 

data = pd.read_csv("Salary_Data.csv")

 

print(data.describe())

 

# Program 205: Write a Python program to access and display the first row of a DataFrame using Pandas.

 

import pandas as pd

 

data = pd.read_csv("Salary_Data.csv")

 

print(data.iloc[0])

 

# Program 206: Write a Python program to create a DataFrame using a list and column names.

 

import pandas as pd

 

header = ["Name", "M1 Score", "M2 Score"]

 

data = [

    ["Sanskar", 62, 80],

    ["Sambriddhi", 45, 56],

    ["Aurora", 85, 98]

]

 

df = pd.DataFrame(data, columns=header)

 

print(df)

 

# Program 207: Write a Python program to create a DataFrame using a dictionary.

import pandas as pd

 

data = {

    "Product": ["Laptop", "Smartphone", "Tablet"],

    "Price": [75000, 15000, 20000],

    "Quantity": [3, 10, 5]

}

 

df = pd.DataFrame(data)

 

print(df)

# Program 208: Write a Python program to create a DataFrame and write it into a CSV file using to_csv().

 

import pandas as pd

 

header = ["Name", "M1 Score", "M2 Score"]

 

data = [

    ["Sanskar", 62, 80],

    ["Sambriddhi", 45, 56],

    ["Aurora", 85, 98]

]

 

df = pd.DataFrame(data, columns=header)

 

df.to_csv("Stu_data.csv", index=False)

 

print("CSV file created successfully.")

 

 

# Program 209: Write a Python program to calculate the total salary from a CSV file using Pandas.

 

import pandas as pd

 

data = pd.read_csv("Salary_Data.csv")

 

total = data["Salary"].sum()

 

print("Total Salary =", total)

 

 

# Program 210: Write a Python program to calculate the average salary from a CSV file using Pandas.

 

import pandas as pd

 

data = pd.read_csv("Salary_Data.csv")

 

average = data["Salary"].mean()

 

print("Average Salary =", average)

 

 

# Program 211: Write a Python program to find the highest and lowest salary from a CSV file using Pandas.

 

import pandas as pd

 

data = pd.read_csv("Salary_Data.csv")

 

print("Highest Salary =", data["Salary"].max())

print("Lowest Salary =", data["Salary"].min())

 

 

# Program 212: Write a Python program to display records of employees whose salary is greater than 50000 using Pandas.

 

import pandas as pd

 

data = pd.read_csv("Salary_Data.csv")

 

result = data[data["Salary"] > 50000]

 

print("Employees with salary above 50000:")

print(result)

 

 

# Program 213: Write a Python program to display records where salary is between 40000 and 60000 using Pandas.

 

import pandas as pd

 

data = pd.read_csv("Salary_Data.csv")

 

result = data[

    (data["Salary"] >= 40000) &

    (data["Salary"] <= 60000)

]

 

print("Salary between 40000 and 60000:")

print(result)

 

# Program 214: Write a Python program to display records where salary is greater than 50000 or experience is greater than 3 years.

 

import pandas as pd

 

data = pd.read_csv("Salary_Data.csv")

 

result = data[

    (data["Salary"] > 50000) |

    (data["Years Experience"] > 3)

]

 

print("Filtered Records:")

print(result)

 

# Program 215: Write a Python program to sort employee records according to salary in ascending order.

 

import pandas as pd

 

data = pd.read_csv("Salary_Data.csv")

 

result = data.sort_values(by="Salary")

 

print("Records in Ascending Order:")

print(result)

# Program 216: Write a Python program to sort employee records according to salary in descending order.

 

import pandas as pd

 

data = pd.read_csv("Salary_Data.csv")

 

result = data.sort_values(by="Salary", ascending=False)

 

print("Records in Descending Order:")

print(result)

 

# Program 217: Write a Python program to display multiple selected columns from a CSV file using Pandas.

 

import pandas as pd

 

data = pd.read_csv("Salary_Data.csv")

 

result = data[["Years Experience", "Salary"]]

 

print("Selected Columns:")

print(result)

 

# Program 218: Write a Python program to add a new column to a DataFrame using Pandas.

 

import pandas as pd

 

data = pd.read_csv("Salary_Data.csv")

 

data["Bonus"] = data["Salary"] * 0.10

 

print("DataFrame with Bonus:")

print(data)

 

# Program 219: Write a Python program to update the salary of employees whose experience is greater than 3 years using Pandas.

 

import pandas as pd

 

data = pd.read_csv("Salary_Data.csv")

 

data.loc[data["Years Experience"] > 3, "Salary"] = 70000

 

print("Updated Employee Records:")

print(data)

 

Program 220: Write a Python program to delete a particular column from a DataFrame using Pandas.

 

import pandas as pd

data = pd.read_csv("Salary_Data.csv")

data = data.drop("Salary", axis=1)

print("DataFrame after deleting Salary column:")

print(data)

 

# Program 221: Write a Python program to draw a bar chart using Python lists and Matplotlib.

 

import matplotlib.pyplot as plt

 

subjects = ["English", "Math", "Science", "Computer"]

marks = [75, 85, 90, 95]

 

plt.bar(subjects, marks, color="blue")

 

plt.title("Student Marks")

plt.xlabel("Subjects")

plt.ylabel("Marks")

 

plt.show()

 

 

# Program 222: Write a Python program to draw a line graph using Python lists and Matplotlib.

 

import matplotlib.pyplot as plt

 

months = ["Jan", "Feb", "Mar", "Apr", "May"]

sales = [100, 150, 120, 200, 250]

 

plt.plot(months, sales, color="green", marker="o", linestyle="-")

 

plt.title("Monthly Sales")

plt.xlabel("Months")

plt.ylabel("Sales")

 

plt.show()

 

 

# Program 223: Write a Python program to draw a scatter plot using Python lists and Matplotlib.

 

import matplotlib.pyplot as plt

 

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

marks = [35, 45, 55, 65, 75, 90]

 

plt.scatter(hours, marks, color="red", marker="o")

 

plt.title("Study Hours and Marks")

plt.xlabel("Study Hours")

plt.ylabel("Marks")

 

plt.show()

 

 

 

 

 

# Program 224: Write a Python program to draw a pie chart using Python lists and Matplotlib.

 

import matplotlib.pyplot as plt

 

subjects = ["English", "Math", "Science", "Computer"]

marks = [75, 85, 90, 95]

 

plt.pie(marks, labels=subjects, autopct="%1.1f%%")

 

plt.title("Subject-wise Marks Distribution")

 

plt.show()

 

# Program 225: Write a Python program to draw a bar chart using Pandas DataFrame and Matplotlib without CSV.

 

import pandas as pd

import matplotlib.pyplot as plt

 

data = {

    "Subject": ["English", "Math", "Science", "Computer"],

    "Marks": [75, 85, 90, 95]

}

 

df = pd.DataFrame(data)

 

plt.bar(df["Subject"], df["Marks"], color="blue")

 

plt.title("Student Marks")

plt.xlabel("Subjects")

plt.ylabel("Marks")

 

plt.show()

 

# Program 226: Write a Python program to draw a line graph using Pandas DataFrame and Matplotlib without CSV.

 

import pandas as pd

import matplotlib.pyplot as plt

 

data = {

    "Month": ["Jan", "Feb", "Mar", "Apr", "May"],

    "Sales": [100, 150, 120, 200, 250]

}

 

df = pd.DataFrame(data)

 

plt.plot(df["Month"], df["Sales"], color="green", marker="o", linestyle="-")

 

plt.title("Monthly Sales")

plt.xlabel("Months")

plt.ylabel("Sales")

 

plt.show()

# Program 227: Write a Python program to draw a scatter plot using Pandas DataFrame and Matplotlib without CSV.

 

import pandas as pd

import matplotlib.pyplot as plt

 

data = {

    "Hours": [1, 2, 3, 4, 5, 6],

    "Marks": [35, 45, 55, 65, 75, 90]

}

 

df = pd.DataFrame(data)

 

plt.scatter(df["Hours"], df["Marks"], color="red", marker="o")

 

plt.title("Study Hours and Marks")

plt.xlabel("Study Hours")

plt.ylabel("Marks")

 

plt.show()

 

# Program 228: Write a Python program to draw a pie chart using Pandas DataFrame and Matplotlib without CSV.

 

import pandas as pd

import matplotlib.pyplot as plt

 

data = {

    "Subject": ["English", "Math", "Science", "Computer"],

    "Marks": [75, 85, 90, 95]

}

 

df = pd.DataFrame(data)

 

plt.pie(df["Marks"], labels=df["Subject"], autopct="%1.1f%%")

 

plt.title("Subject-wise Marks Distribution")

 

plt.show()

 

# Program 229: Write a Python program to draw a bar chart using Pandas DataFrame and Matplotlib with CSV.

 

import pandas as pd

import matplotlib.pyplot as plt

 

df = pd.read_csv("student.csv")

 

plt.bar(df["Subject"], df["Marks"], color="blue")

 

plt.title("Student Marks")

plt.xlabel("Subjects")

plt.ylabel("Marks")

 

plt.show()

# Program 230: Write a Python program to draw a line graph using Pandas DataFrame and Matplotlib with CSV.

 

import pandas as pd

import matplotlib.pyplot as plt

 

df = pd.read_csv("sales.csv")

 

plt.plot(df["Month"], df["Sales"], color="green", marker="o", linestyle="-")

 

plt.title("Monthly Sales")

plt.xlabel("Months")

plt.ylabel("Sales")

 

plt.show()

 

 

# Program 231: Write a Python program to draw a scatter plot using Pandas DataFrame and Matplotlib with CSV.

 

import pandas as pd

import matplotlib.pyplot as plt

 

df = pd.read_csv("student.csv")

 

plt.scatter(df["Hours"], df["Marks"], color="red", marker="o")

 

plt.title("Study Hours and Marks")

plt.xlabel("Study Hours")

plt.ylabel("Marks")

 

plt.show()

 

 

# Program 232: Write a Python program to draw a pie chart using Pandas DataFrame and Matplotlib with CSV.

 

import pandas as pd

import matplotlib.pyplot as plt

 

df = pd.read_csv("student.csv")

 

plt.pie(df["Marks"], labels=df["Subject"], autopct="%1.1f%%")

 

plt.title("Subject-wise Marks Distribution")

 

plt.show()

 

 

 

 

 

 

 

 

# Program 233: Write a Python program to draw a horizontal bar chart using Matplotlib.

 

import matplotlib.pyplot as plt

 

subjects = ["English", "Math", "Science", "Computer"]

marks = [75, 85, 90, 95]

 

plt.barh(subjects, marks, color="green")

 

plt.title("Student Marks")

plt.xlabel("Marks")

plt.ylabel("Subjects")

 

plt.show()

 

# Program 234: Write a Python program to draw multiple line graphs with a legend using Matplotlib.

 

import matplotlib.pyplot as plt

 

months = ["Jan", "Feb", "Mar", "Apr", "May"]

 

sales_2025 = [100, 150, 120, 200, 250]

sales_2026 = [120, 180, 160, 220, 280]

 

plt.plot(months, sales_2025, color="blue", marker="o", label="2025")

plt.plot(months, sales_2026, color="red", marker="s", label="2026")

 

plt.title("Monthly Sales Comparison")

plt.xlabel("Months")

plt.ylabel("Sales")

 

plt.legend()

 

plt.show()

 

# Program 235: Write a Python program to draw a bar chart and save it as an image using Matplotlib.

 

import matplotlib.pyplot as plt

 

subjects = ["English", "Math", "Science", "Computer"]

marks = [75, 85, 90, 95]

 

plt.bar(subjects, marks, color="orange")

 

plt.title("Student Marks")

plt.xlabel("Subjects")

plt.ylabel("Marks")

 

plt.savefig("student_marks.png")

plt.show()

 

print("Graph saved successfully.")

 

# Program 236: Write a Python program to draw a bar chart using Python lists and Seaborn.

 

import seaborn as sns

import matplotlib.pyplot as plt

 

subjects = ["English", "Math", "Science", "Computer"]

marks = [75, 85, 90, 95]

 

sns.barplot(x=subjects, y=marks, color="skyblue")

 

plt.title("Student Marks")

plt.xlabel("Subjects")

plt.ylabel("Marks")

 

plt.show()

 

 

# Program 237: Write a Python program to draw a line graph using Python lists and Seaborn.

 

import seaborn as sns

import matplotlib.pyplot as plt

 

months = ["Jan", "Feb", "Mar", "Apr", "May"]

sales = [100, 150, 120, 200, 250]

 

sns.lineplot(x=months, y=sales, marker="o", color="green")

 

plt.title("Monthly Sales")

plt.xlabel("Months")

plt.ylabel("Sales")

 

plt.show()

 

 

# Program 238: Write a Python program to draw a scatter plot using Python lists and Seaborn.

 

import seaborn as sns

import matplotlib.pyplot as plt

 

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

marks = [35, 45, 55, 65, 75, 90]

 

sns.scatterplot(x=hours, y=marks, color="red")

 

plt.title("Study Hours and Marks")

plt.xlabel("Study Hours")

plt.ylabel("Marks")

 

plt.show()

 

 

# Program 239: Write a Python program to draw a histogram using Python lists and Seaborn.

import seaborn as sns

import matplotlib.pyplot as plt

 

marks = [45, 55, 60, 65, 70, 75, 80, 85, 90, 95]

 

sns.histplot(marks, bins=5, color="blue")

 

plt.title("Distribution of Student Marks")

plt.xlabel("Marks")

plt.ylabel("Frequency")

 

plt.show()

 

# Program 240: Write a Python program to draw a bar chart using Pandas DataFrame and Seaborn without CSV.

import pandas as pd

import seaborn as sns

import matplotlib.pyplot as plt

 

data = {

    "Subject": ["English", "Math", "Science", "Computer"],

    "Marks": [75, 85, 90, 95]

}

 

df = pd.DataFrame(data)

 

sns.barplot(data=df, x="Subject", y="Marks", color="skyblue")

 

plt.title("Student Marks")

plt.xlabel("Subjects")

plt.ylabel("Marks")

 

plt.show()

 

# Program 241: Write a Python program to draw a line graph using Pandas DataFrame and Seaborn without CSV.

import pandas as pd

import seaborn as sns

import matplotlib.pyplot as plt

 

data = {

    "Month": ["Jan", "Feb", "Mar", "Apr", "May"],

    "Sales": [100, 150, 120, 200, 250]

}

 

df = pd.DataFrame(data)

 

sns.lineplot(data=df, x="Month", y="Sales", marker="o", color="green")

plt.title("Monthly Sales")

plt.xlabel("Months")

plt.ylabel("Sales")

 

plt.show()

# Program 242: Write a Python program to draw a scatter plot using Pandas DataFrame and Seaborn without CSV.

import pandas as pd

import seaborn as sns

import matplotlib.pyplot as plt

 

data = {

    "Hours": [1, 2, 3, 4, 5, 6],

    "Marks": [35, 45, 55, 65, 75, 90]

}

 

df = pd.DataFrame(data)

 

sns.scatterplot(data=df, x="Hours", y="Marks", color="red")

 

plt.title("Study Hours and Marks")

plt.xlabel("Study Hours")

plt.ylabel("Marks")

 

plt.show()

 

# Program 243: Write a Python program to draw a histogram using Pandas DataFrame and Seaborn without CSV.

import pandas as pd

import seaborn as sns

import matplotlib.pyplot as plt

 

data = {

    "Marks": [45, 55, 60, 65, 70, 75, 80, 85, 90, 95]

}

 

df = pd.DataFrame(data)

 

sns.histplot(data=df, x="Marks", bins=5, color="blue")

 

plt.title("Distribution of Student Marks")

plt.xlabel("Marks")

plt.ylabel("Frequency")

 

plt.show()

 

# Program 244: Write a Python program to draw a bar chart using Pandas DataFrame and Seaborn with CSV.

import pandas as pd

import seaborn as sns

import matplotlib.pyplot as plt

 

df = pd.read_csv("student.csv")

 

sns.barplot(data=df, x="Subject", y="Marks", color="skyblue")

 

plt.title("Student Marks")

plt.xlabel("Subjects")

plt.ylabel("Marks")

plt.show()

# Program 245: Write a Python program to draw a line graph using Pandas DataFrame and Seaborn with CSV.

 

import pandas as pd

import seaborn as sns

import matplotlib.pyplot as plt

 

df = pd.read_csv("sales.csv")

 

sns.lineplot(data=df, x="Month", y="Sales", marker="o", color="green")

 

plt.title("Monthly Sales")

plt.xlabel("Months")

plt.ylabel("Sales")

 

plt.show()

 

 

# Program 246: Write a Python program to draw a scatter plot using Pandas DataFrame and Seaborn with CSV.

 

import pandas as pd

import seaborn as sns

import matplotlib.pyplot as plt

 

df = pd.read_csv("student.csv")

 

sns.scatterplot(data=df, x="Hours", y="Marks", color="red")

 

plt.title("Study Hours and Marks")

plt.xlabel("Study Hours")

plt.ylabel("Marks")

 

plt.show()

 

 

# Program 247: Write a Python program to draw a histogram using Pandas DataFrame and Seaborn with CSV.

 

import pandas as pd

import seaborn as sns

import matplotlib.pyplot as plt

 

df = pd.read_csv("student.csv")

 

sns.histplot(data=df, x="Marks", bins=5, color="blue")

 

plt.title("Distribution of Student Marks")

plt.xlabel("Marks")

plt.ylabel("Frequency")

 

plt.show()

 

 

 

# Program 248: Write a Python program to draw a bar chart using Python lists and Plotly.

 

import plotly.express as px

 

subjects = ["English", "Math", "Science", "Computer"]

marks = [75, 85, 90, 95]

 

fig = px.bar(

    x=subjects,

    y=marks,

    title="Student Marks",

    labels={"x": "Subjects", "y": "Marks"}

)

 

fig.show()

 

 

# Program 249: Write a Python program to draw a line graph using Python lists and Plotly.

 

import plotly.express as px

 

months = ["Jan", "Feb", "Mar", "Apr", "May"]

sales = [100, 150, 120, 200, 250]

 

fig = px.line(

    x=months,

    y=sales,

    markers=True,

    title="Monthly Sales",

    labels={"x": "Months", "y": "Sales"}

)

 

fig.show()

 

 

# Program 250: Write a Python program to draw a scatter plot using Python lists and Plotly.

 

import plotly.express as px

 

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

marks = [35, 45, 55, 65, 75, 90]

 

fig = px.scatter(

    x=hours,

    y=marks,

    title="Study Hours and Marks",

    labels={"x": "Study Hours", "y": "Marks"}

)

 

fig.show()

 

 

# Program 251: Write a Python program to draw a pie chart using Python lists and Plotly.

 

import plotly.express as px

 

subjects = ["English", "Math", "Science", "Computer"]

marks = [75, 85, 90, 95]

 

fig = px.pie(

    names=subjects,

    values=marks,

    title="Subject-wise Marks Distribution"

)

 

fig.show()

 

 

# Program 252: Write a Python program to draw a bar chart using Pandas DataFrame and Plotly without CSV.

 

import pandas as pd

import plotly.express as px

 

data = {

    "Subject": ["English", "Math", "Science", "Computer"],

    "Marks": [75, 85, 90, 95]

}

 

df = pd.DataFrame(data)

 

fig = px.bar(df, x="Subject", y="Marks", title="Student Marks")

 

fig.show()

 

 

# Program 253: Write a Python program to draw a line graph using Pandas DataFrame and Plotly without CSV.

 

import pandas as pd

import plotly.express as px

 

data = {

    "Month": ["Jan", "Feb", "Mar", "Apr", "May"],

    "Sales": [100, 150, 120, 200, 250]

}

 

df = pd.DataFrame(data)

 

fig = px.line(

    df, x="Month", y="Sales",

    markers=True, title="Monthly Sales"

)

 

fig.show()

 

# Program 254: Write a Python program to draw a scatter plot using Pandas DataFrame and Plotly without CSV.

 

import pandas as pd

import plotly.express as px

 

data = {

    "Hours": [1, 2, 3, 4, 5, 6],

    "Marks": [35, 45, 55, 65, 75, 90]

}

 

df = pd.DataFrame(data)

 

fig = px.scatter(

    df, x="Hours", y="Marks",

    title="Study Hours and Marks"

)

 

fig.show()

 

# Program 255: Write a Python program to draw a pie chart using Pandas DataFrame and Plotly without CSV.

 

import pandas as pd

import plotly.express as px

 

data = {

    "Subject": ["English", "Math", "Science", "Computer"],

    "Marks": [75, 85, 90, 95]

}

 

df = pd.DataFrame(data)

 

fig = px.pie(

    df,

    names="Subject",

    values="Marks",

    title="Subject-wise Marks Distribution"

)

 

fig.show()

 

# Program 256: Write a Python program to draw a bar chart using Pandas DataFrame and Plotly with CSV.

 

import pandas as pd

import plotly.express as px

 

df = pd.read_csv("student.csv")

 

fig = px.bar(

    df, x="Subject", y="Marks",

    title="Student Marks"

)

fig.show()

# Program 257: Write a Python program to draw a line graph using Pandas DataFrame and Plotly with CSV.

import pandas as pd

import plotly.express as px

 

df = pd.read_csv("sales.csv")

 

fig = px.line(

    df, x="Month", y="Sales",

    markers=True, title="Monthly Sales"

)

 

fig.show()

 

# Program 258: Write a Python program to draw a scatter plot using Pandas DataFrame and Plotly with CSV.

import pandas as pd

import plotly.express as px

 

df = pd.read_csv("student.csv")

 

fig = px.scatter(

    df, x="Hours", y="Marks",

    title="Study Hours and Marks"

)

 

fig.show()

 

# Program 259: Write a Python program to draw a pie chart using Pandas DataFrame and Plotly with CSV.

import pandas as pd

import plotly.express as px

 

df = pd.read_csv("student.csv")

 

fig = px.pie(

    df,

    names="Subject",

    values="Marks",

    title="Subject-wise Marks Distribution"

)

 

fig.show()

Program 260: Write a Python program to draw a histogram using Python lists and Plotly.

import plotly.express as px

 

marks = [45, 55, 60, 65, 70, 75, 80, 85, 90, 95]

fig = px.histogram(

    x=marks,

    nbins=5,

    title="Distribution of Student Marks",

    labels={"x": "Marks", "y": "Frequency"}

)

fig.show()

B. Code Practice – All 23 Questions

Basic Python and User-Defined Functions

1. Write a Python program that asks any two numbers and displays the greater one.

2. Write a Python program that asks the length, breadth, and height of a room. Create a user-defined function to calculate the area of the floor. Use another function to calculate the volume of the room.

Hint:

  • Area = Length × Breadth
  • Volume = Length × Breadth × Height

3. Write a Python program that asks for the length in feet and converts it to inches.

Hint: 1 foot = 12 inches.

4. Write a Python program that asks three different numbers and calculates the product and average. Use a function for product and a subprogram for average.

5. Write a program to calculate the area of a square using a function. The user should input the side length.

6. Write a program that calculates the Total Surface Area of a cuboid using a function.

Hint: TSA = 2(lb + bh + hl)

7. Write a Python program to calculate the perimeter of a square using a subprogram.

Hint: Perimeter = 4 × L

8. Write a Python program to calculate the circumference of a circle using a subprogram.

Hint: Circumference = 2Ï€r

9. Write a program to calculate the total surface area of a sphere using a subprogram.

Hint: TSA = 4Ï€r²

10. Write a program to calculate the curved surface area (CSA) of a cuboid.

Hint: CSA = 2h(l + b)

Series and Mathematical Operations

11. Write a Python program using a subprogram to generate the series:

2, 3, 5, 8, 13, 21, 34

Generate up to 10 terms and calculate the sum of the series.

12. Write a Python program to find the sum of digits of a number using a user-defined function.

Example: If the user enters 123, the result should be 6.

13. Write a Python program to display the multiplication table of a number up to 10 using a user-defined function.

14. Write a Python program to find the factorial of a number using a user-defined function.

Example: 5! = 5 × 4 × 3 × 2 × 1 = 120.

File Handling

15. Write a Python program to create a file named student.txt and store the name and class of 3 students.

16. Write a Python program to read and display the content of student.txt.

17. Write a Python program to add (append) one more student's name and class to the existing file student.txt.

Series and Functions – Additional Question

18. Write a Python program to generate this series using a function:

2, 3, 5, 8, 13, 21, 34

Generate up to 10 terms and also calculate and display the sum of the series.

Functions and Arithmetic Operations

19. Write a Python program to input two numbers and calculate:

  • Sum
  • Product
  • Difference

Use three separate functions for each calculation.

Pandas and CSV File Handling

20. A file named employee.csv stores Name, Address, Gender, and Salary.

Write a Python program to show the records of employees who earn more than 75,000.

21. A file named result.csv stores data with columns:

Symbol No, Name, Gender, English, Nepali, Maths, Computer

Write a Python program to display the records of students:

  • Whose gender is 'M'
  • Who scored more than 85 in Computer.

22. A file named employee.csv contains data with fields:

Name, Address, Gender, Salary

Write a Python program to display the data of employees with salary more than 50,000.

23. A file named record.csv contains columns:

Roll No, Name, Gender, English, Nepali, Maths, Computer

Write a Python program to display the records of students:

  • Whose gender is 'F'
  • Who scored more than 90 in Computer.

 

Sample Programs – Questions Only

1. Write a program to take two numbers as input and print their sum.

2. Write a program to check if a number is positive, negative, or zero.

3. Write a program to ask for the user's age and determine if they are an adult or not.

4. Write a Python program to create a new file and write a message into it.

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

6. Write a function to check if a number is even or odd.

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

8. Write a program using a for loop to print numbers from 1 to 10.

9. Write a program using a while loop to find the sum of the first 10 natural numbers.

10. Write a program to print all even numbers from 1 to 20 using a for loop.

11. Write a function to calculate simple interest using a default argument for the rate of interest.