0% found this document useful (0 votes)
8 views56 pages

Python Practical File for BCA Students

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views56 pages

Python Practical File for BCA Students

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Practical File

On

PYTHON
Submitted to
MAHARSHI DAYANAND UNIVERSITY, ROHTAK
In partial fulfillment of the requirements for the award of the degree of
BACHELOR OF COMPUTER APPLICATIONS
(Regular Degree)
(5thSEMESTER)
Submitted by

Name: Anchal Sharma


REG. No: 235103005
INDEX

Page
S No. Topic Name Remarks
No.
1 Calculation of salary 3
2 Calculate Gross salary 4-5

3 Numerical grade to letter grade 6

4 Smallest among three variables 7

5 Character is vowel or consonant 8


6 Calculate the electricity bill 9-10
Calculate sum of all numbers from 1 11
7
to given number
8 Print table of given number 12
9 Count total no. of digits 13
10 Print list in reverse order using loop 14
11 Draw square spiral using turtle 15-16
12 Make a clock using python 17-19
13 Print colorful spiral of user’s name 20-22
14 Calendar in GUI process 23-24
15 Tic Tac Toe game design 25-28
Simple Registration form using 29-31
16
Tkinter
Create database, table and record 32-33
17
insert
18 Customize meme generator using 34-36

-1-
Tkinter and GUI Module

Page
S No. Topic Name Remarks
No.
19 Colorful star making using Turtle 37-38
20 Music player using Python 39-41

21 Banking management using Python 42-45

22 Age calculator using Tkinter 46-48

Program that asks user to enter their 49


23
age and their name
Image crop and resize using 50-51
24
OpenCV

25 Create Sudoku design game 52-55

-2-
Q1. The calculation of salary based on hours worked is,

• Hours worked = 8, payment = 1500.


• Hours worked < 8; pay less, 75 per hour.
• Hours worked > 8; pay more, 75 per hour.

PROGRAM:

hours = int(input("Enter number of hours worked: "))

if hours == 8:

salary = 1500

elif hours < 8:

salary = hours * 75

else:

salary = (8 * 75) + ((hours - 8) * 75)

'''Output for result'''

print ("Total salary is:", salary)

Output:

-3-
-4-
Q.2 Calculate the Gross Salary of an employee for following allowance
& deduction.
• Get Basic Salary of Employee,
• DA = 25% of Basic,
• HRA = 15% of Basic,
• PF = 12% of Basic,
• TA = 7.50% of Basic.
• Net Pay = Basic + DA + HRA + TA
• Gross Pay = Net Pay - PF.

PROGRAM:

basic = float(input("Enter the basic salary of the employee: "))

DA = 0.25*basic
HRA = 0.15*basic
PF = 0.12*basic
TA = 0.075*basic

net_pay = basic + DA + HRA + TA

gross_pay = net_pay - PF

print ("\n----- Salary Details -----")


print ("Basic Salary : ₹", basic)
print ("DA (25%) : ₹", DA)
print ("HRA (15%) : ₹", HRA)
print ("TA (7.5%) : ₹", TA)
print ("PF (12%) : ₹", PF)
print ("Net Pay : ₹", net_pay)
print ("Gross Pay : ₹", gross_pay)

-5-
Output:

-6-
Q.3 I want to make a piece of code that converts from a numerical grade
(35 -100) to a letter grade (A, B, C, D, F).

PROGRAM:

grade = int(input("Enter the numerical grade (35-100): "))

'''check and convert to letter grade '''


if grade >= 90:
letter = 'A'
elif grade >= 80:
letter = "B"
elif grade >= 70:
letter = "C"
elif grade >= 60:
letter = "D"
elif grade >= 35:
letter = "F"
else:
letter = "Invalid (Below passing marks)"

print ("The letter grade is: ",letter)

Output:

-7-
Q.4 WAP to find which one is smallest given the three variables.

PROGRAM:

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


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

'''compare to find the smallest'''

if a < b and a < c:


print (f"{a} is the smallest number.")
elif b < c:
print (f"{b} is the smallest number.")
else:
print (f"{c} is the smallest number.")

Output:

-8-
Q.5 Python program to check whether the entered character is vowel or
consonant.
PROGRAM:

ch = input("Enter a single alphabet: ")

'''convert to lower case for easy comparison'''


if len (ch) == 1 and [Link]():
if ch in ['a', 'e', 'i', 'o', 'u']:
print(f"{ch} is a vowel.")
else:
print (f"{ch} is a consonant.")
else:
print ("Please enter a single alphabet only!")

Output:

-9-
Q.6 Write a program to calculate the electricity bill (accept number of
unit from user) according to the following criteria.
Unit Price
First 100 units no charge
Next 100 units Rs 5 per unit
After 100 units Rs 10 per unit
If input unit is 350 than total bill amount is Rs 2000.

PROGRAM:

units = int(input("Enter the number of units consumed :"))


'''calculate the bill'''
if units <= 100:
bill = 0
elif units <= 200:
bill = (units - 100) * 5
else:
bill = (100 * 5) + (units - 200) * 10
print ("Total electricity bill: Rs", bill)

- 10 -
Output:

Q.7 Calculate the sum of all numbers from 1 to a given number.

PROGRAM:

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

'''calculate the sum'''


total = 0
for i in range(1, n+1):
total += i

print("The sum of numbers from 1 to", n, "is:", total)

Output:

- 11 -
Q.8 Write a program to print multiplication table of a given number.

PROGRAM:

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

'''Print the multiplication table'''


print("Multiplication Table of", num)

for i in range(1, 11):


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

Output:

- 12 -
Q.9 Count the total number of digits in a number.

PROGRAM:

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

'''Initialize a counter'''
count = 0

'''count digits using a loop'''


while num > 0:
count += 1
num //= 10

print ("The total number of digits: ", count)

- 13 -
Output:

Q.10 Print the list in reverse order using a loop.

PROGRAM:

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

'''print list in reverse using a loop'''

print ("List in reverse order: ")

for i in range(len(numbers) -1, -1, -1):


print(numbers[i])

Output:

- 14 -
Q.11 Draw a square spiral using turtle.

PROGRAM:

import turtle

def draw_square_spiral(side_start=5, step=5, turns=60, pen_size=2,


speed=0):
"""
Draws a square spiral.
- side_start: starting length of the first side (pixels)
- step: how much the side length grows each segment (pixels)
- turns: total number of line segments (more -> bigger spiral)
- pen_size: thickness of the line
- speed: turtle speed (0 = fastest, 1..10 slower)
"""

- 15 -
t = [Link]()
screen = [Link]()
[Link]("Square Spiral")
[Link]("black")

[Link]()
[Link](pen_size)
[Link](speed)
[Link]("cyan")
[Link]()
[Link](0, 0)
[Link]()
[Link]()

side = side_start
for i in range(turns):
[Link](side)
[Link](90)
side += step
if i % 10 == 0:

colors = ["cyan", "magenta", "yellow", "white", "orange"]


[Link](colors[(i // 10) % len(colors)])

[Link]()

if __name__ == "__main__":

draw_square_spiral(side_start=5, step=5, turns=80, pen_size=2,


speed=0)

Output:

- 16 -
Q.12 Make a clock using python.

PROGRAM:

import turtle
import time
from datetime import datetime

screen = [Link]()
[Link]("Analog Clock")
[Link]("black")
[Link](width=600, height=600)
pen = [Link]()

- 17 -
[Link]()
[Link](0)
[Link](3)
[Link]("cyan")

def draw_clock(h, m, s, pen):


[Link]()
[Link](0, 210)
[Link](180)
[Link]("white")
[Link]()
[Link](210)

[Link]()
[Link](0, 0)
[Link](90)
for _ in range(12):
[Link](180)
[Link]()
[Link](20)
[Link]()
[Link](0, 0)
[Link](30)

[Link]()
[Link](0, 0)
[Link]("cyan")
[Link](90)
angle = (h / 12) * 360 + (m / 60) * 30
[Link](angle)
[Link]()
[Link](100)

[Link]()
[Link](0, 0)

- 18 -
[Link]("green")
[Link](90)
angle = (m / 60) * 360
[Link](angle)
[Link]()
[Link](150)

[Link]()
[Link](0, 0)
[Link]("red")
[Link](90)
angle = (s / 60) * 360
[Link](angle)
[Link]()
[Link](180)

while True:
[Link]()

now = [Link]()
h = [Link] % 12
m = [Link]
s = [Link]

draw_clock(h, m, s, pen)
[Link]()
[Link](1)

Output:

- 19 -
Q.13 Print a colorful spiral of the user's name.

PROGRAM:

import turtle
import colorsys

def name_spiral(name,
turns=500,
start_distance=4,
- 20 -
distance_step=1.8,
angle_step=15,
start_font=10,
font_growth=0.03,
speed=0):
"""
Draw a colorful spiral using the provided name.
- name: string to draw (will repeat if short)
- turns: how many characters/steps to draw (more -> larger spiral)
- start_distance: initial forward movement (pixels)
- distance_step: how much forward distance increases each step
- angle_step: degrees to rotate at each step
- start_font: starting font size
- font_growth: amount font size increases per step
- speed: turtle speed (0 fastest)
"""
if not name:
raise ValueError("Name must not be empty")

screen = [Link]()
[Link](800, 800)
[Link]("Colorful Name Spiral")
[Link]("black")

t = [Link]()
[Link]()
[Link]()
[Link](0, 0)
[Link]()
[Link](speed)
[Link](1.0)

distance = start_distance
font_size = start_font
n = len(name)
- 21 -
for i in range(turns):
ch = name[i % n]
hue = (i / turns) % 1.0
r, g, b = colorsys.hsv_to_rgb(hue, 1.0, 1.0)
[Link](r, g, b)

[Link]()
[Link](distance)
[Link]()

[Link](ch, align="center", font=("Arial", int(max(6, font_size)),


"bold")

[Link]()
[Link](distance)
[Link]()

[Link](angle_step)
distance += distance_step
font_size += font_growth

[Link]()
[Link]()
[Link]()
if __name__ == "__main__":
name = input("Enter your name: ").strip()

name_spiral(name,
turns=700,
start_distance=6,
distance_step=2.0,
angle_step=13,
start_font=8,
font_growth=0.04,
- 22 -
speed=0)

Output:

Q.14 Calendar in GUI process

PROGRAM:

import tkinter as tk
import calendar
from datetime import datetime

def show_calendar():
month = month_var.get()
- 23 -
year = year_var.get()
cal_text = [Link](year, month)
[Link](text=cal_text)

root = [Link]()
[Link]("Calendar")

month_var = [Link](value=[Link]().month)
year_var = [Link](value=[Link]().year)

[Link](root, text="Month:").pack()
[Link](root, from_=1, to=12, textvariable=month_var,
width=5).pack()

[Link](root, text="Year:").pack()
[Link](root, from_=1900, to=2100, textvariable=year_var,
width=5).pack()

[Link](root, text="Show Calendar",


command=show_calendar).pack(pady=10)

label = [Link](root, font=("Courier", 14), justify="left")


[Link](pady=10)

[Link]()

Output:

- 24 -
Q.15 Tic Tac Toe game design in python.

PROGRAM:

- 25 -
board = [" " for _ in range(9)]
'''Function to display the board'''
def print_board():
print("\n")
print(f" {board[0]} | {board[1]} | {board[2]} ")
print("---+---+---")
print(f" {board[3]} | {board[4]} | {board[5]} ")
print("---+---+---")
print(f" {board[6]} | {board[7]} | {board[8]} ")
print("\n")

''' Check for winner'''


def check_winner(player):
win_conditions = [
[0, 1, 2], [3, 4, 5], [6, 7, 8], # rows
[0, 3, 6], [1, 4, 7], [2, 5, 8], # columns
[0, 4, 8], [2, 4, 6] # diagonals ]
for condition in win_conditions:
if board[condition[0]] == board[condition[1]] ==
board[condition[2]] == player:
return True
return False

''' Check if the board is full'''


def is_draw():
return " " not in board

''' Main game function'''


def play_game():
current_player = "X"
print("Welcome to Tic Tac Toe!")
print_board()

while True:
'''Ask player for their move'''
- 26 -
try:
move = int(input(f"Player {current_player}, choose your
position(1-9): ")) -1
except ValueError:
print("Invalid input. Please enter a number between 1 and 9.")
continue

'''Validate the move'''


if move < 0 or move > 8:
print("Invalid position! Choose between 1 and 9.")
continue
if board[move] != " ":
print("That position is already taken. Try again.")
continue

''' Make the move'''


board[move] = current_player
print_board()

'''Check for a winner'''


if check_winner(current_player):
print(f"🎉 Player {current_player} wins!")
break

'''Check for a draw'''


if is_draw():
print("🤝 It's a draw!")
break

''' Switch player'''


current_player = "O" if current_player == "X" else "X"
'''Start the game'''
play_game()

- 27 -
Output:

- 28 -
Q.16 Simple Registration forms using Tkinter in Python.

PROGRAM:
- 29 -
import tkinter as tk
from tkinter import messagebox

'''Function to handle form submission'''


def submit_form():
name = name_entry.get()
email = email_entry.get()
gender = gender_var.get()
password = password_entry.get()

if name == "" or email == "" or gender == "" or password == "":


[Link]("Input Error", "Please fill all fields!")
else:
[Link]("Registration Successful", f"Welcome,
{name}!")
''' Optional: clear fields after submission'''
name_entry.delete(0, [Link])
email_entry.delete(0, [Link])
password_entry.delete(0, [Link])
gender_var.set("")

'''Create main window'''


root = [Link]()
[Link]("Registration Form")
[Link]("350x300")
[Link](False, False)

'''Heading'''
title_label = [Link](root, text="User Registration Form",
font=("Arial", 16, "bold"))
title_label.pack(pady=10)

'''Name'''

- 30 -
[Link](root, text="Full Name:", font=("Arial", 12)).pack(anchor='w',
padx=30)
name_entry = [Link](root, width=30)
name_entry.pack(padx=30, pady=5)

'''Email'''
[Link](root, text="Email:", font=("Arial", 12)).pack(anchor='w',
padx=30)
email_entry = [Link](root, width=30)
email_entry.pack(padx=30, pady=5)

'''Gender'''
[Link](root, text="Gender:", font=("Arial", 12)).pack(anchor='w',
padx=30)
gender_var = [Link]()
[Link](root, text="Male", variable=gender_var,
value="Male").pack(anchor='w', padx=40)
[Link](root, text="Female", variable=gender_var,
value="Female").pack(anchor='w', padx=40)

'''Password'''
[Link](root, text="Password:", font=("Arial", 12)).pack(anchor='w',
padx=30)
password_entry = [Link](root, width=30, show="*")
password_entry.pack(padx=30, pady=5)

'''Submit button'''
submit_btn = [Link](root, text="Register", width=15, bg="blue",
fg="white", command=submit_form)
submit_btn.pack(pady=15)

- 31 -
'''Run the application'''
[Link]()

Output:

Q.17 Create database, table and record insert using python.

PROGRAM:

import sqlite3

'''Connect to a database (or create one if it doesn't exist) '''


conn = [Link]("[Link]") # creates '[Link]' file
cursor = [Link]()

'''Create a table'''
[Link]("""
CREATE TABLE IF NOT EXISTS students (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
age INTEGER,
email TEXT UNIQUE)
""")
print("✅ Table 'students' created successfully!")

'''Insert records'''

- 32 -
[Link]("INSERT INTO students (name, age, email) VALUES
(?, ?, ?)",
("Alice", 20, "alice@[Link]"))
[Link]("INSERT INTO students (name, age, email) VALUES
(?, ?, ?)",
("Bob", 22, "bob@[Link]"))

'''Commit changes and close connection'''


[Link]()
print("✅ Records inserted successfully!")

''' (Optional) Fetch and display all records'''


[Link]("SELECT * FROM students")
rows = [Link]()
print("\n📊 All Records:")
for row in rows:
print(row)

'''Close the database'''


[Link]()

Output:

- 33 -
Q.18 Customize a meme generator using Tkinter or GUI Module.

PROGRAM:

import tkinter as tk
from tkinter import filedialog, messagebox
from tkinter import PhotoImage

''' Global variables'''


img_label = None
img = None

- 34 -
'''Function to load an image'''
def load_image():
global img, img_label
file_path = [Link](
title="Select Image",
filetypes=[("PNG Images", "*.png"), ("GIF Images", "*.gif")] )
if not file_path:
return

img = PhotoImage(file=file_path)

img_label.config(image=img)
img_label.image = img

'''Function to generate meme text'''


def generate_meme():
top_text = top_text_entry.get().upper()
bottom_text = bottom_text_entry.get().upper()

if img is None:
[Link]("No Image", "Please load an image
first!")
return

'''Update labels with text'''


top_label.config(text=top_text)
bottom_label.config(text=bottom_text)
'''Create GUI window'''
root = [Link]()
[Link]("Meme Generator (No PIL)")
[Link]("600x700")
[Link](False, False)

''' Title'''

- 35 -
[Link](root, text="📸 Meme Generator", font=("Arial", 22,
"bold")).pack(pady=10)

'''Image display'''
img_frame = [Link](root, width=500, height=400, bg="black")
img_frame.pack(pady=10)

img_label = [Link](img_frame, bg="black")


img_label.place(relx=0.5, rely=0.5, anchor="center")

'''Meme Text Labels'''


top_label = [Link](img_frame, text="", font=("Impact", 24, "bold"),
fg="white", bg="black")
top_label.place(relx=0.5, rely=0.05, anchor="n")

bottom_label = [Link](img_frame, text="", font=("Impact", 24,


"bold"), fg="white", bg="black")
bottom_label.place(relx=0.5, rely=0.95, anchor="s")

''' Text input'''


[Link](root, text="Top Text:", font=("Arial", 12)).pack()
top_text_entry = [Link](root, width=40, font=("Arial", 12))
top_text_entry.pack(pady=5)
[Link](root, text="Bottom Text:", font=("Arial", 12)).pack()
bottom_text_entry = [Link](root, width=40, font=("Arial", 12))
bottom_text_entry.pack(pady=5)

'''Buttons'''
[Link](root, text="📁 Load Image", font=("Arial", 12),
command=load_image).pack(pady=10)
[Link](root, text="💥 Generate Meme", font=("Arial", 12),
bg="blue", fg="white", command=generate_meme).pack(pady=10)
[Link]()

- 36 -
Output:

Q.19 Colorful star making using turtle.

PROGRAM:

import turtle
import random

screen = [Link]()
[Link]("black")
[Link]("Multicolored 5-Point Star")

- 37 -
t = [Link]()
[Link]()
[Link](0)
[Link](4)

''' list of colors to pick from'''


colors = ["red", "orange", "yellow", "green", "cyan", "blue", "magenta",
"white"]

'''move to nicer starting position'''


[Link]()
[Link](0, -50)
[Link]()

'''draw 5-point star, changing color each stroke'''


points = 5
angle = 180 - 180/points # exterior angle for a star
length = 250

for i in range(points * 2): # multiply so strokes criss-cross nicely


[Link]([Link](colors))
[Link](length)
[Link](angle)
[Link]()

Output:

- 38 -
Q.20 Music player using python

PROGRAM:

import tkinter as tk
from tkinter import filedialog, messagebox
import winsound
import threading

music_file = None

- 39 -
'''Load .wav file'''
def load_music():
global music_file
music_file = [Link]
( title="Select a WAV file",
filetypes=[("WAV Files", "*.wav")] )
if music_file:
song_label.config(text=f"🎵 Loaded: {music_file.split('/')[-1]}")

'''Play music in background (so GUI doesn't freeze) '''


def play_music():
if music_file is None:
[Link]("No File", "Please load a WAV file
first!")
return
[Link](target=lambda: [Link](music_file,
winsound.SND_FILENAME)).start()

'''Stop music'''
def stop_music():
[Link](None, winsound.SND_PURGE)

'''GUI setup'''
root = [Link]()
[Link]("🎶 Simple Music Player (No Install)")
[Link]("400x300")
[Link](bg="#2c2c2c")

'''Title'''
[Link](root, text="🎧 Python Music Player", font=("Arial", 20,
"bold"), bg="#2c2c2c", fg="white").pack(pady=20)

'''Song label'''

- 40 -
song_label = [Link](root, text="No file loaded", font=("Arial", 12),
bg="#2c2c2c", fg="cyan")
song_label.pack(pady=10)

'''Buttons'''
[Link](root, text="📁 Load Music (.wav)", font=("Arial", 14),
width=20, command=load_music).pack(pady=10)
[Link](root, text="▶ Play", font=("Arial", 14), width=20,
bg="green", fg="white", command=play_music).pack(pady=10)
[Link](root, text="⏹ Stop", font=("Arial", 14), width=20, bg="red",
fg="white", command=stop_music).pack(pady=10)

[Link](root, text="⚠️ Only .wav files supported (built-in)",


font=("Arial", 10), bg="#2c2c2c", fg="yellow").pack(pady=20)

[Link]()

Output

- 41 -
Q21. Banking management using python.

PROGRAM:

class BankAccount:
def __init__(self, account_number, name, balance=0):
self.account_number = account_number
[Link] = name
[Link] = balance

def deposit(self, amount):


if amount > 0:
[Link] += amount
print(f"✅ Rs.{amount} deposited successfully!")
else:
print("❌ Invalid deposit amount.")

def withdraw(self, amount):


if amount > [Link]:
print("❌ Insufficient balance!")
elif amount <= 0:
print("❌ Invalid withdrawal amount.")
else:
[Link] -= amount
print(f"✅ Rs.{amount} withdrawn successfully!")

def display_balance(self):
print(f"💰 Account Balance: Rs.{[Link]}")

- 42 -
def display_details(self):
print("\n📄 Account Details:")
print(f"Account Number: {self.account_number}")
print(f"Account Holder: {[Link]}")
print(f"Balance: Rs.{[Link]}")

'''Dictionary to store accounts'''


accounts = {}

def create_account():
account_number = input("Enter Account Number: ")
if account_number in accounts:
print("❌ Account already exists!")
return

name = input("Enter Account Holder Name: ")


initial_deposit = float(input("Enter Initial Deposit: Rs."))
accounts[account_number] = BankAccount(account_number, name,
initial_deposit)
print("✅ Account created successfully!")

def deposit_money():
acc_no = input("Enter Account Number: ")
if acc_no in accounts:
amount = float(input("Enter amount to deposit: Rs."))
accounts[acc_no].deposit(amount)
else:
print("❌ Account not found!")

def withdraw_money():
acc_no = input("Enter Account Number: ")
if acc_no in accounts:
amount = float(input("Enter amount to withdraw: Rs."))
accounts[acc_no].withdraw(amount)

- 43 -
else:
print("❌ Account not found!")

def check_balance():
acc_no = input("Enter Account Number: ")
if acc_no in accounts:
accounts[acc_no].display_balance()
else:
print("❌ Account not found!")

def view_details():
acc_no = input("Enter Account Number: ")
if acc_no in accounts:
accounts[acc_no].display_details()
else:
print("❌ Account not found!")
'''Menu-driven program'''
while True:
print("\n===== 🏦 Banking Management System =====")
print("1. Create Account")
print("2. Deposit Money")
print("3. Withdraw Money")
print("4. Check Balance")
print("5. View Account Details")
print("6. Exit")

choice = input("Enter your choice: ")


if choice == "1":
create_account()
elif choice == "2":
deposit_money()
elif choice == "3":
withdraw_money()
elif choice == "4":

- 44 -
check_balance()
elif choice == "5":
view_details()
elif choice == "6":
print("👋 Thank you for using our banking system!")
break
else:
print("❌ Invalid choice! Please try again.")

Output:

Q.22 AGE CALCULATOR using Tkinter.

PROGRAM:

import tkinter as tk
from tkinter import messagebox
from datetime import date

- 45 -
'''Function to calculate age'''
def calculate_age():
try:
birth_year = int(year_entry.get())
birth_month = int(month_entry.get())
birth_day = int(day_entry.get())

today = [Link]()
birth_date = date(birth_year, birth_month, birth_day)

'''Calculate age'''
age = [Link] - birth_date.year
if ([Link], [Link]) < (birth_date.month, birth_date.day):
age -= 1

[Link]("Age Calculator", f"You are {age} years


old!")
except ValueError:
[Link]("Invalid Input", "Please enter valid numbers
for year, month, and day.")
except Exception as e:
[Link]("Error", str(e))

'''Create main window'''


root = [Link]()
[Link]("Age Calculator")
[Link]("300x250")
[Link](False, False)

'''Labels'''
[Link](root, text="Enter your Birth Date", font=("Arial",
14)).pack(pady=10)

- 46 -
[Link](root, text="Date").pack()
day_entry = [Link](root)
day_entry.pack()

[Link](root, text="Month").pack()
month_entry = [Link](root)
month_entry.pack()

[Link](root, text="Year").pack()
year_entry = [Link](root)
year_entry.pack()

'''Calculate button'''
[Link](root, text="Calculate Age", command=calculate_age,
bg="lightblue").pack(pady=15)

[Link]()

Output:

- 47 -
Q.23 Create a program that asks the user to enter their name and age.
Print out a message addressed to them that tells them the year that they
will turn 100 years old, except don’t explicitly write out the year. Use the
built-in Python date time library to make the code you write work during
every year, not just the one we are currently in.

PROGRAM:

from datetime import date

'''Ask user for name and age'''


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

'''Get the current year'''


- 48 -
current_year = [Link]().year

'''Calculate the year they will turn 100'''


year_turn_100 = current_year + (100 - age)
print(f"Hello {name}! You will turn 100 years old in {year_turn_100}.")

Output:

Q.24 Image crop and resize using OpenCV.

PROGRAM:

import cv2
# Load the image
img = [Link]("[Link]") # Replace with your image file name

# Show original image


[Link]("Original Image", img)

# Get image dimensions


h, w, c = [Link]
print(f"Original Dimensions: {w}x{h}")

# Crop the image [y:y+h, x:x+w]

- 49 -
cropped_img = img[50:250, 100:300] # You can change coordinates as
needed

# Resize the cropped image


resized_img = [Link](cropped_img, (200, 200)) # width x height

# Display results
[Link]("Cropped Image", cropped_img)
[Link]("Resized Image", resized_img)

# Save results (optional)


[Link]("cropped_output.jpg", cropped_img)
[Link]("resized_output.jpg", resized_img)

[Link](0)
[Link]()

Output:

- 50 -
Q.25 Create Sudoku game design in pygame.

PROGRAM:

import pygame
import sys
# Initialize pygame
[Link]()
# Screen setup
WIDTH, HEIGHT = 540, 600
WIN = [Link].set_mode((WIDTH, HEIGHT))
[Link].set_caption("Sudoku Game")
# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
LIGHTBLUE = (96, 216, 232)
LOCKEDCELLCOLOUR = (189, 189, 189)

- 51 -
INCORRECTCELLCOLOUR = (195, 121, 121)
# Fonts
font = [Link]("comicsans", 40)
font_small = [Link]("comicsans", 20)
# Board (0 means empty cell)
board = [
[7, 8, 0, 4, 0, 0, 1, 2, 0],
[6, 0, 0, 0, 7, 5, 0, 0, 9],
[0, 0, 0, 6, 0, 1, 0, 7, 8],
[0, 0, 7, 0, 4, 0, 2, 6, 0],
[0, 0, 1, 0, 5, 0, 9, 3, 0],
[9, 0, 4, 0, 6, 0, 0, 0, 5],
[0, 7, 0, 3, 0, 0, 0, 1, 2],
[1, 2, 0, 0, 0, 7, 4, 0, 0],
[0, 4, 9, 2, 0, 6, 0, 0, 7]
]

# Variables
selected = None
cell_size = WIDTH // 9

def draw_grid():
"""Draw Sudoku grid lines."""
for i in range(10):
if i % 3 == 0:
thick = 4
else:
thick = 1
[Link](WIN, BLACK, (0, i * cell_size), (WIDTH, i *
cell_size), thick)
[Link](WIN, BLACK, (i * cell_size, 0), (i * cell_size,
WIDTH), thick)

def draw_numbers():

- 52 -
"""Draw numbers on the board."""
for i in range(9):
for j in range(9):
if board[i][j] != 0:
text = [Link](str(board[i][j]), True, BLACK)
[Link](text, (j * cell_size + 20, i * cell_size + 10))

def highlight_cell(pos):
"""Highlight selected cell."""
if pos:
[Link](WIN, LIGHTBLUE, (pos[1]*cell_size,
pos[0]*cell_size, cell_size, cell_size), 3)

def get_pos(mouse_pos):
"""Get grid position from mouse coordinates."""
if mouse_pos[0] < WIDTH and mouse_pos[1] < WIDTH:
x = mouse_pos[0] // cell_size
y = mouse_pos[1] // cell_size
return (y, x)
return None

def redraw_window():
[Link](WHITE)
draw_grid()
draw_numbers()
highlight_cell(selected)
[Link]()

def main():
global selected
run = True

while run:
for event in [Link]():

- 53 -
if [Link] == [Link]:
run = False

if [Link] == [Link]:
pos = [Link].get_pos()
selected = get_pos(pos)

if [Link] == [Link]:
if selected:
y, x = selected
if [Link] == pygame.K_DELETE or [Link] ==
pygame.K_BACKSPACE:
board[y][x] = 0
elif pygame.K_1 <= [Link] <= pygame.K_9:
board[y][x] = [Link] - pygame.K_0

redraw_window()
[Link]()
[Link]()

if _name_ == "_main_":
main()

Output:

- 54 -
- 55 -

You might also like