0% found this document useful (0 votes)
3 views54 pages

Programing

The document contains a series of programming exercises in Python, covering various topics such as tax calculation, leap year determination, triangle classification, ATM withdrawal logic, BMI calculation, and basic arithmetic operations. Each exercise includes a description, difficulty level, and sample code with expected outputs. The exercises are designed to enhance understanding of conditional statements, logical operators, and match-case constructs in Python.

Uploaded by

yasirqazi1975
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)
3 views54 pages

Programing

The document contains a series of programming exercises in Python, covering various topics such as tax calculation, leap year determination, triangle classification, ATM withdrawal logic, BMI calculation, and basic arithmetic operations. Each exercise includes a description, difficulty level, and sample code with expected outputs. The exercises are designed to enhance understanding of conditional statements, logical operators, and match-case constructs in Python.

Uploaded by

yasirqazi1975
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

If Else Condition:

Q1 — Tax Bracket Calculator Difficulty: Hard

Write a program that takes an annual income and calculates the total tax owed using Pakistan's 5-
slab tax system. Each slab has its own rate, and only the income within each slab is taxed at that
slab's rate.

python
income = float(input("Enter annual income (PKR): "))

tax = 0

if income <= 600000:


tax = 0
elif income <= 1200000:
tax = (income - 600000) * 0.05
elif income <= 2400000:
tax = 30000 + (income - 1200000) * 0.15
elif income <= 3600000:
tax = 210000 + (income - 2400000) * 0.25
elif income <= 6000000:
tax = 510000 + (income - 3600000) * 0.30
else:
tax = 1230000 + (income - 6000000) * 0.35

print(f"Annual Income : PKR {income:,.0f}")


print(f"Total Tax : PKR {tax:,.0f}")
print(f"Effective Rate: {(tax/income)*100:.2f}%" if income > 0 else "N/A")

Sample Output (income = 2,000,000):

Annual Income : PKR 2,000,000


Total Tax : PKR 150,000
Effective Rate: 7.50%

Q2 — Leap Year & Days in Month Difficulty: Hard

Take a month number (1–12) and a year. Print how many days that month has, correctly handling
leap years for February.

python
month = int(input("Enter month (1-12): "))
year = int(input("Enter year: "))

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


is_leap = True
else:
is_leap = False

if month in [1, 3, 5, 7, 8, 10, 12]:


days = 31
elif month in [4, 6, 9, 11]:
days = 30
elif month == 2:
if is_leap:
days = 29
else:
days = 28
else:
print("Invalid month!")
exit()

month_names = ["","January","February","March","April","May","June",
"July","August","September","October","November","December"]

print(f"{month_names[month]} {year} has {days} days.")


if is_leap:
print(f"({year} is a leap year)")

Sample Output (month=2, year=2024):

February 2024 has 29 days.


(2024 is a leap year)

Q3 — Triangle Classifier Difficulty: Hard

Given three side lengths, check if they form a valid triangle. If valid, classify it as equilateral,
isosceles, or scalene, AND as acute, right, or obtuse.

python
a = float(input("Side a: "))
b = float(input("Side b: "))
c = float(input("Side c: "))

if a <= 0 or b <= 0 or c <= 0:


print("Sides must be positive.")
elif (a + b <= c) or (a + c <= b) or (b + c <= a):
print("Not a valid triangle.")
else:
if a == b == c:
side_type = "Equilateral"
elif a == b or b == c or a == c:
side_type = "Isosceles"
else:
side_type = "Scalene"

sides = sorted([a, b, c])


sq_sum = sides[0]**2 + sides[1]**2
sq_hyp = sides[2]**2

if sq_sum == sq_hyp:
angle_type = "Right"
elif sq_sum > sq_hyp:
angle_type = "Acute"
else:
angle_type = "Obtuse"

print(f"Valid triangle: {side_type} & {angle_type}")

Sample Output (3, 4, 5):

Valid triangle: Scalene & Right

Q4 — ATM Withdrawal Logic Difficulty: Hard

Simulate an ATM: check PIN, enforce a daily withdrawal limit, a minimum balance rule, and
only allow amounts that are multiples of 500 PKR.

python
CORRECT_PIN = "1234"
balance = 85000.0
DAILY_LIMIT = 50000
MIN_BALANCE = 1000
DENOMINATION = 500

pin = input("Enter PIN: ")

if pin != CORRECT_PIN:
print("Incorrect PIN. Card blocked after 3 wrong attempts.")
else:
amount = float(input("Enter withdrawal amount (PKR): "))

if amount <= 0:
print("Amount must be positive.")
elif amount % DENOMINATION != 0:
print(f"Amount must be a multiple of PKR {DENOMINATION}.")
elif amount > DAILY_LIMIT:
print(f"Exceeds daily limit of PKR {DAILY_LIMIT:,}.")
elif (balance - amount) < MIN_BALANCE:
print(f"Insufficient funds. Must keep PKR {MIN_BALANCE:,} minimum.")
else:
balance -= amount
print(f"PKR {amount:,.0f} dispensed successfully.")
print(f"Remaining balance: PKR {balance:,.0f}")

Sample Output (correct PIN, amount=20000):

PKR 20,000 dispensed successfully.


Remaining balance: PKR 65,000

Q5 — BMI Category with Health Advice Difficulty: Hard

Calculate BMI from weight and height, classify it across 6 WHO categories, and give different
advice depending on whether the person is under 18 or an adult.

python
weight = float(input("Weight (kg): "))
height = float(input("Height (m): "))
age = int(input("Age (years): "))

if weight <= 0 or height <= 0 or age <= 0:


print("All values must be positive.")
else:
bmi = weight / (height ** 2)
print(f"\nBMI: {bmi:.1f}")

if bmi < 16:


category = "Severe Thinness"
advice = "Immediate medical attention required."
elif bmi < 17:
category = "Moderate Thinness"
advice = "Consult a nutritionist urgently."
elif bmi < 18.5:
category = "Mild Thinness"
advice = "Increase caloric intake gradually."
elif bmi < 25:
category = "Normal"
advice = "Maintain current diet and exercise."
elif bmi < 30:
category = "Overweight"
advice = "Reduce sugar intake; 30 min cardio daily."
else:
category = "Obese"
advice = "Consult a doctor for a structured plan."

print(f"Category: {category}")

if age < 18:


print(f"Note (under 18): BMI norms differ for children.")
print(f"Please consult a paediatrician.")
else:
print(f"Advice: {advice}")

Sample Output (70 kg, 1.75 m, age 25):

BMI: 22.9
Category: Normal
Advice: Maintain current diet and exercise.

Question 1 (Easy)

Find the area and perimeter of a rectangle

Formula:

 Area = length × width


 Perimeter = 2 × (length + width)

Solution:
length = float(input("Enter length: "))
width = float(input("Enter width: "))

area = length * width


perimeter = 2 * (length + width)

print("Area:", area)
print("Perimeter:", perimeter)

Question 2 (Easy → Medium)

Convert temperature from Celsius to Fahrenheit

👉 Formula:
F = (C × 9/5) + 32

Solution:
celsius = float(input("Enter temperature in Celsius: "))

fahrenheit = (celsius * 9/5) + 32

print("Temperature in Fahrenheit:", fahrenheit)

Question 3 (Medium)

Calculate simple interest

👉 Formula:
SI = (P × R × T) / 100

Where:
P = Principal, R = Rate, T = Time

Solution:
p = float(input("Enter principal: "))
r = float(input("Enter rate: "))
t = float(input("Enter time: "))

si = (p * r * t) / 100

print("Simple Interest:", si)

Question 4 (Medium → Hard)

Calculate total salary

Conditions:
 Basic salary entered by user
 HRA = 20% of basic
 DA = 10% of basic
 Total Salary = Basic + HRA + DA

Solution:
basic = float(input("Enter basic salary: "))

hra = basic * 0.20


da = basic * 0.10

total_salary = basic + hra + da

print("Total Salary:", total_salary)

Question 5 (Hard)

Swap two numbers WITHOUT using third variable

Use arithmetic operators only

Solution:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))

a = a + b
b = a - b
a = a - b

print("After swapping:")
print("a =", a)
print("b =", b)
Comparison Operators
Question 1:
Write a program that takes three integers from the user and determines whether they are strictly
increasing, strictly decreasing, or neither using only comparison operators.

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

if a < b and b < c:


print("Strictly Increasing")
elif a > b and b > c:
print("Strictly Decreasing")
else:
print("Neither")

Question 2:
Write a program that checks whether a given year is a leap year using comparison operators.

Condition:
A year is a leap year if:

 It is divisible by 4 AND not divisible by 100


OR
 It is divisible by 400

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

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


print("Leap Year")
else:
print("Not a Leap Year")

Question 3:
Write a program that takes a number and checks whether it lies within two given ranges:
Range1: 10 to 50
Range2: 100 to 200
Use comparison operators to determine the result.

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

if (num >= 10 and num <= 50) or (num >= 100 and num <= 200):
print("Number is within the valid ranges")
else:
print("Number is outside the ranges")

Question 4:
Write a program that takes two numbers and checks if they are equal without using the equality
operator (==). Use only other comparison operators.

Answer:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))

if not (a < b or a > b):


print("Numbers are equal")
else:
print("Numbers are not equal")

Question 5:
Write a program that takes three numbers and finds the greatest among them using only
comparison operators (no max function).

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

if a >= b and a >= c:


print("Greatest is:", a)
elif b >= a and b >= c:
print("Greatest is:", b)
else:
print("Greatest is:", c)

Logical Operators
Question 1:
Write a program that takes a username and password and checks access using logical operators.
Access is granted only if:

 Username is "admin" AND password is "1234"


 OR username is "guest" AND password is "guest123"

Answer:
username = input("Enter username: ")
password = input("Enter password: ")

if (username == "admin" and password == "1234") or (username == "guest" and password ==


"guest123"):
print("Access Granted")
else:
print("Access Denied")

Question 2:
Write a program that takes a number and determines whether it is a positive even number OR a
negative odd number using logical operators.

Answer:
num = int(input("Enter a number: "))
if (num > 0 and num % 2 == 0) or (num < 0 and num % 2 != 0):
print("Condition Satisfied")
else:
print("Condition Not Satisfied")

Question 3:
Write a program that checks whether a character entered by the user is a vowel (a, e, i, o, u)
using logical operators only.

Answer:
ch = input("Enter a character: ")

if ch == 'a' or ch == 'e' or ch == 'i' or ch == 'o' or ch == 'u':


print("Vowel")
else:
print("Not a Vowel")

Question 4:
Write a program that determines if a student is eligible for admission. Eligibility criteria:

 Marks in Math, Physics, and Chemistry are entered


 Student is eligible if:
(Math >= 65 AND Physics >= 55 AND Chemistry >= 50)
OR
(Total of all three >= 190)

Answer:
math = int(input("Enter Math marks: "))
physics = int(input("Enter Physics marks: "))
chemistry = int(input("Enter Chemistry marks: "))

total = math + physics + chemistry

if (math >= 65 and physics >= 55 and chemistry >= 50) or (total >= 190):
print("Eligible for admission")
else:
print("Not eligible")

Question 5:
Write a program that takes three boolean inputs (True/False) and determines the result of a
complex logical expression:
Result is True if:

 At least two values are True


 AND not all three are True
Answer:
a = input("Enter True/False for a: ") == "True"
b = input("Enter True/False for b: ") == "True"
c = input("Enter True/False for c: ") == "True"

if ((a and b) or (a and c) or (b and c)) and not (a and b and c):
print("Result: True")
else:
print("Result: False")

Match Case
Question 1:
Write a program that takes a number and checks multiple properties using match-case:

 If number is divisible by both 3 and 5 → print "FizzBuzz"


 If only divisible by 3 → print "Fizz"
 If only divisible by 5 → print "Buzz"
 Otherwise → print "None"

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

match (num % 3 == 0, num % 5 == 0):


case (True, True):
print("FizzBuzz")
case (True, False):
print("Fizz")
case (False, True):
print("Buzz")
case _:
print("None")

Question 2:
Write a program that takes a character and classifies it using match-case:

 Uppercase vowel
 Lowercase vowel
 Uppercase consonant
 Lowercase consonant
 Digit
 Special character

Answer:
ch = input("Enter a character: ")
match ch:
case 'A' | 'E' | 'I' | 'O' | 'U':
print("Uppercase Vowel")
case 'a' | 'e' | 'i' | 'o' | 'u':
print("Lowercase Vowel")
case _ if [Link]() and [Link]():
print("Uppercase Consonant")
case _ if [Link]() and [Link]():
print("Lowercase Consonant")
case _ if [Link]():
print("Digit")
case _:
print("Special Character")

Question 3:
Write a program that takes three numbers and an operator (+, -, *, /, //, %, **) and performs the
operation using match-case. If operator is invalid, print error.

Answer:
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
op = input("Enter operator: ")

match op:
case '+':
print("Result:", a + b)
case '-':
print("Result:", a - b)
case '*':
print("Result:", a * b)
case '/':
if b != 0:
print("Result:", a / b)
else:
print("Division by zero error")
case '//':
if b != 0:
print("Result:", a // b)
else:
print("Division by zero error")
case '%':
if b != 0:
print("Result:", a % b)
else:
print("Division by zero error")
case '**':
print("Result:", a ** b)
case _:
print("Invalid operator")

Question 4:
Write a program that takes a tuple of three values (day, month, year) and uses match-case with
pattern matching:

 If date is (1, 1, any year) → print "New Year"


 If date is (25, 12, any year) → print "Christmas"
 If day > 31 or month > 12 → print "Invalid Date"
 Otherwise → print "Normal Day"

Answer:
day = int(input("Enter day: "))
month = int(input("Enter month: "))
year = int(input("Enter year: "))

match (day, month, year):


case (1, 1, _):
print("New Year")
case (25, 12, _):
print("Christmas")
case (d, m, _) if d > 31 or m > 12:
print("Invalid Date")
case _:
print("Normal Day")

Question 5:
Write a program that takes a list of exactly 3 numbers and uses match-case to:

 Check if all are equal → print "All Equal"


 Check if strictly increasing → print "Increasing"
 Check if strictly decreasing → print "Decreasing"
 Otherwise → print "Mixed"

Answer:
nums = list(map(int, input("Enter three numbers separated by space: ").split()))

match nums:
case [a, b, c] if a == b == c:
print("All Equal")
case [a, b, c] if a < b < c:
print("Increasing")
case [a, b, c] if a > b > c:
print("Decreasing")
case [_, _, _]:
print("Mixed")
case _:
print("Invalid Input")

while loop
Question 1:
Write a program that keeps taking numbers from the user until the user enters 0. For each
number:

 Skip negative numbers using continue


 If number is positive, add it to sum
 If number is greater than 100, stop the loop using break
Finally, print the sum of valid numbers.

Answer:
total = 0

while True:
num = int(input("Enter number (0 to stop): "))

if num == 0:
break

if num < 0:
continue

if num > 100:


break

total += num

print("Sum of valid numbers:", total)

Question 2:
Write a program that asks the user to enter a number and checks if it is a prime number using a
while loop.

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

if num <= 1:
print("Not Prime")
else:
i=2
is_prime = True
while i <= num // 2:
if num % i == 0:
is_prime = False
break
i += 1

if is_prime:
print("Prime Number")
else:
print("Not Prime")

Question 3:
Write a program that keeps asking the user for a password until the correct password "admin123"
is entered. After 3 wrong attempts, stop the program using break.

Answer:
correct_password = "admin123"
attempts = 0

while True:
password = input("Enter password: ")
attempts += 1

if password == correct_password:
print("Access Granted")
break
else:
print("Wrong Password")

if attempts == 3:
print("Too many attempts. Access Denied")
break

Question 4:
Write a program that reverses a number using a while loop. Example: 1234 → 4321

Answer:
num = int(input("Enter a number: "))
reverse = 0

while num > 0:


digit = num % 10
reverse = reverse * 10 + digit
num = num // 10

print("Reversed number:", reverse)

Question 5:
Write a program that continuously takes numbers from the user and:
 Count how many numbers are divisible by 3
 Count how many numbers are divisible by 5
 Stop when user enters -1
 Skip numbers divisible by both 3 and 5 using continue

Answer:
count3 = 0
count5 = 0

while True:
num = int(input("Enter number (-1 to stop): "))

if num == -1:
break

if num % 3 == 0 and num % 5 == 0:


continue

if num % 3 == 0:
count3 += 1

if num % 5 == 0:
count5 += 1

print("Divisible by 3:", count3)


print("Divisible by 5:", count5)

FOR LOOP QUESTIONS

Question 1:
Write a program that prints all numbers between 1 and 200 that are divisible by 7 but not
divisible by 5.

Answer:
for i in range(1, 201):
if i % 7 == 0 and i % 5 != 0:
print(i)

Question 2:
Write a program that finds the factorial of a number using a for loop. If the number is negative,
print "Invalid input".

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

if num < 0:
print("Invalid input")
else:
fact = 1
for i in range(1, num + 1):
fact *= i
print("Factorial:", fact)

Question 3:
Write a program that takes 10 numbers from the user and finds:

 Maximum number
 Minimum number

Answer:
nums = []

for i in range(10):
n = int(input("Enter number: "))
[Link](n)

max_num = nums[0]
min_num = nums[0]

for n in nums:
if n > max_num:
max_num = n
if n < min_num:
min_num = n

print("Maximum:", max_num)
print("Minimum:", min_num)

Question 4:
Write a program that prints the following pattern using nested for loop:

1
12
123
1234
12345

Answer:
for i in range(1, 6):
for j in range(1, i + 1):
print(j, end="")
print()
Question 5:
Write a program that checks whether a number is an Armstrong number using a for loop.

Answer:
num = int(input("Enter a number: "))
power = len(str(num))
sum_val = 0

for digit in str(num):


sum_val += int(digit) ** power

if sum_val == num:
print("Armstrong Number")
else:
print("Not an Armstrong Number")

DO-WHILE LOOP QUESTIONS (Python Simulation)

Note: Python does not have a built-in do-while loop, so we simulate it using while True.

Question 1:
Write a program that keeps asking the user for a number until the user enters a positive number.

Answer:
while True:
num = int(input("Enter a number: "))
if num > 0:
print("Valid number entered:", num)
break
else:
print("Invalid, try again")

Question 2:
Write a program that keeps taking input numbers and prints their square. Stop when the user
enters 0.

Answer:
while True:
num = int(input("Enter number (0 to stop): "))
print("Square:", num * num)
if num == 0:
break

Question 3:
Write a program that simulates a menu:
1. Add
2. Subtract
3. Exit
Keep running until the user chooses Exit.

Answer:
while True:
print("1. Add")
print("2. Subtract")
print("3. Exit")

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

if choice == 3:
break

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


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

if choice == 1:
print("Result:", a + b)
elif choice == 2:
print("Result:", a - b)
else:
print("Invalid choice")

Question 4:
Write a program that keeps asking for a password until the correct one is entered. After correct
entry, print "Welcome".

Answer:
correct = "python123"

while True:
pwd = input("Enter password: ")
if pwd == correct:
print("Welcome")
break
else:
print("Wrong password")

Question 5:
Write a program that keeps taking numbers and prints whether they are even or odd. Stop only
when user enters -1.

Answer:
while True:
num = int(input("Enter number (-1 to stop): "))
if num == -1:
break

if num % 2 == 0:
print("Even")
else:
print("Odd")

Question 1:
Write a program to check whether a number is a palindrome (same forward and backward).

Answer:
num = int(input("Enter a number: "))
original = num
reverse = 0

while num > 0:


digit = num % 10
reverse = reverse * 10 + digit
num //= 10

if original == reverse:
print("Palindrome")
else:
print("Not Palindrome")

Question 2:
Write a program to find the second largest number in a list of n numbers entered by the user.

Answer:
n = int(input("Enter count: "))
nums = []

for i in range(n):
[Link](int(input("Enter number: ")))

largest = second = float('-inf')

for num in nums:


if num > largest:
second = largest
largest = num
elif num > second and num != largest:
second = num

print("Second Largest:", second)


Question 3:
Write a program to count frequency of each digit in a number.

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

for d in "0123456789":
count = 0
for ch in num:
if ch == d:
count += 1
if count > 0:
print(d, ":", count)

Question 4:
Write a program to print all prime numbers between 1 and 100.

Answer:
for num in range(2, 101):
is_prime = True
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
is_prime = False
break
if is_prime:
print(num)

Question 5:
Write a program to find the sum of series:
1 + 11 + 111 + 1111 + ... up to n terms.

Answer:
n = int(input("Enter number of terms: "))
term = 0
total = 0

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


term = term * 10 + 1
total += term
print("Sum:", total)

Question 6:
Write a program to check whether two strings are anagrams.

Answer:
s1 = input("Enter first string: ")
s2 = input("Enter second string: ")

if sorted(s1) == sorted(s2):
print("Anagram")
else:
print("Not Anagram")

Question 7:
Write a program to print Fibonacci series up to n terms.

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

a, b = 0, 1

for i in range(n):
print(a, end=" ")
a, b = b, a + b

Question 8:
Write a program to remove duplicates from a list without using built-in set.

Answer:
n = int(input("Enter number of elements: "))
nums = []

for i in range(n):
[Link](int(input("Enter number: ")))

unique = []
for num in nums:
if num not in unique:
[Link](num)

print("Unique list:", unique)

Question 9:
Write a program to find whether a number is a perfect number.
(A number is perfect if sum of its divisors excluding itself equals the number)

Answer:
num = int(input("Enter a number: "))
sum_div = 0

for i in range(1, num):


if num % i == 0:
sum_div += i

if sum_div == num:
print("Perfect Number")
else:
print("Not Perfect")

Question 10:
Write a program to implement a simple calculator using loop. Keep running until user chooses
exit.

Answer:
while True:
print("[Link] [Link] [Link] [Link] [Link]")
choice = int(input("Enter choice: "))

if choice == 5:
break

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


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

if choice == 1:
print("Result:", a + b)
elif choice == 2:
print("Result:", a - b)
elif choice == 3:
print("Result:", a * b)
elif choice == 4:
if b != 0:
print("Result:", a / b)
else:
print("Division by zero error")
else:
print("Invalid choice")
LIST QUESTIONS (5)

Question 1:
Write a program to find the second smallest element in a list.

Answer:
nums = list(map(int, input("Enter numbers: ").split()))

smallest = second = float('inf')

for num in nums:


if num < smallest:
second = smallest
smallest = num
elif num < second and num != smallest:
second = num

print("Second Smallest:", second)

Question 2:
Write a program to rotate a list to the right by k positions.

Answer:
nums = list(map(int, input("Enter numbers: ").split()))
k = int(input("Enter k: "))

k = k % len(nums)
rotated = nums[-k:] + nums[:-k]

print("Rotated List:", rotated)

Question 3:
Write a program to count how many times each element appears in a list.

Answer:
nums = list(map(int, input("Enter numbers: ").split()))
count_dict = {}

for num in nums:


if num in count_dict:
count_dict[num] += 1
else:
count_dict[num] = 1

print(count_dict)

Question 4:
Write a program to find all pairs in a list whose sum equals a given number.

Answer:
nums = list(map(int, input("Enter numbers: ").split()))
target = int(input("Enter target sum: "))

for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
print(nums[i], nums[j])

Question 5:
Write a program to remove all even numbers from a list.

Answer:
nums = list(map(int, input("Enter numbers: ").split()))

result = []

for num in nums:


if num % 2 != 0:
[Link](num)

print("List after removal:", result)

TUPLE QUESTIONS (5)

Question 1:
Write a program to find the maximum and minimum values in a tuple.
Answer:
t = tuple(map(int, input("Enter tuple values: ").split()))

max_val = t[0]
min_val = t[0]

for num in t:
if num > max_val:
max_val = num
if num < min_val:
min_val = num

print("Max:", max_val)
print("Min:", min_val)

Question 2:
Write a program to count occurrences of an element in a tuple.

Answer:
t = tuple(map(int, input("Enter tuple values: ").split()))
x = int(input("Enter element to count: "))

count = 0

for num in t:
if num == x:
count += 1

print("Count:", count)

Question 3:
Write a program to convert a tuple into a list and remove duplicates.

Answer:
t = tuple(map(int, input("Enter tuple values: ").split()))

lst = list(t)
unique = []

for num in lst:


if num not in unique:
[Link](num)
print("Without duplicates:", unique)

Question 4:
Write a program to find index of a given element in a tuple.

Answer:
t = tuple(map(int, input("Enter tuple values: ").split()))
x = int(input("Enter element: "))

index = -1

for i in range(len(t)):
if t[i] == x:
index = i
break

print("Index:", index)

Question 5:
Write a program to unpack a tuple into variables and find their sum.

Answer:
t = tuple(map(int, input("Enter three values: ").split()))

a, b, c = t

print("Sum:", a + b + c)

SET QUESTIONS (5)

Question 1:
Write a program to find union and intersection of two sets.

Answer:
set1 = set(map(int, input("Enter set1: ").split()))
set2 = set(map(int, input("Enter set2: ").split()))

print("Union:", set1 | set2)


print("Intersection:", set1 & set2)
Question 2:
Write a program to check if one set is subset of another.

Answer:
set1 = set(map(int, input("Enter set1: ").split()))
set2 = set(map(int, input("Enter set2: ").split()))

if [Link](set2):
print("set1 is subset of set2")
else:
print("Not a subset")

Question 3:
Write a program to remove common elements from two sets.

Answer:
set1 = set(map(int, input("Enter set1: ").split()))
set2 = set(map(int, input("Enter set2: ").split()))

result1 = set1 - set2


result2 = set2 - set1

print("Set1 unique:", result1)


print("Set2 unique:", result2)

Question 4:
Write a program to find symmetric difference between two sets.

Answer:
set1 = set(map(int, input("Enter set1: ").split()))
set2 = set(map(int, input("Enter set2: ").split()))

print("Symmetric Difference:", set1 ^ set2)

Question 5:
Write a program to count unique elements in a list using set.
Answer:
nums = list(map(int, input("Enter numbers: ").split()))

unique_set = set(nums)

print("Unique count:", len(unique_set))

DICTIONARY QUESTIONS (5)

Question 1:
Write a program to count frequency of each character in a string using dictionary.

Answer:
s = input("Enter string: ")

freq = {}

for ch in s:
if ch in freq:
freq[ch] += 1
else:
freq[ch] = 1

print(freq)

Question 2:
Write a program to merge two dictionaries.

Answer:
d1 = {"a": 1, "b": 2}
d2 = {"c": 3, "d": 4}

[Link](d2)

print("Merged Dictionary:", d1)

Question 3:
Write a program to find the key with maximum value in dictionary.
Answer:
d = {"a": 10, "b": 25, "c": 15}

max_key = None
max_val = float('-inf')

for key in d:
if d[key] > max_val:
max_val = d[key]
max_key = key

print("Key with max value:", max_key)

Question 4:
Write a program to invert a dictionary (swap keys and values).

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

inv = {}

for key in d:
inv[d[key]] = key

print("Inverted:", inv)

Question 5:
Write a program to group numbers by even and odd using dictionary.

Answer:
nums = list(map(int, input("Enter numbers: ").split()))

result = {"even": [], "odd": []}

for num in nums:


if num % 2 == 0:
result["even"].append(num)
else:
result["odd"].append(num)

print(result)
Functions
Question 1:
Write a function that accepts variable number of arguments (*args) and returns:

 sum of even numbers


 product of odd numbers

Answer:
def process_numbers(*args):
even_sum = 0
odd_product = 1

for num in args:


if num % 2 == 0:
even_sum += num
else:
odd_product *= num

return even_sum, odd_product

result = process_numbers(1, 2, 3, 4, 5)
print(result)

Question 2:
Write a recursive function to calculate power (x^y) without using ** operator.

Answer:
def power(x, y):
if y == 0:
return 1
return x * power(x, y - 1)

print(power(2, 5))

Question 3:
Write a function using lambda and map to square all numbers in a list.

Answer:
nums = [1, 2, 3, 4, 5]
result = list(map(lambda x: x * x, nums))
print(result)
Question 4:
Write a higher-order function that takes another function and a list, and applies the function only
to even numbers.

Answer:
def apply_to_even(func, lst):
result = []
for num in lst:
if num % 2 == 0:
[Link](func(num))
return result

def square(x):
return x * x

print(apply_to_even(square, [1, 2, 3, 4, 5]))

Question 5:
Write a function that demonstrates closure. The outer function should take a number and inner
function should multiply it with another number.

Answer:
def outer(x):
def inner(y):
return x * y
return inner

multiply_by_5 = outer(5)
print(multiply_by_5(3))

Question 6:
Write a decorator function that prints "Function Started" and "Function Ended" before and after
execution.

Answer:
def my_decorator(func):
def wrapper():
print("Function Started")
func()
print("Function Ended")
return wrapper

@my_decorator
def say_hello():
print("Hello")

say_hello()

Question 7:
Write a function that uses default mutable argument and explain its behavior by showing
repeated calls.

Answer:
def add_item(item, lst=[]):
[Link](item)
return lst

print(add_item(1))
print(add_item(2))
print(add_item(3))

Question 8:
Write a generator function that yields Fibonacci numbers up to n terms.

Answer:
def fibonacci(n):
a, b = 0, 1
count = 0

while count < n:


yield a
a, b = b, a + b
count += 1

for num in fibonacci(5):


print(num)

Question 9:
Write a function that returns another function and keeps track of how many times it has been
called.
Answer:
def counter():
count = 0
def inner():
nonlocal count
count += 1
return count
return inner

c = counter()
print(c())
print(c())
print(c())

Question 10:
Write a function that takes a list and returns:

 a list of prime numbers


 count of non-prime numbers
Use helper function inside.

Answer:
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True

def analyze_list(lst):
primes = []
non_prime_count = 0

for num in lst:


if is_prime(num):
[Link](num)
else:
non_prime_count += 1

return primes, non_prime_count

print(analyze_list([1, 2, 3, 4, 5, 6, 7]))

Error handling
Question 1:
Write a program that takes two numbers and performs division. Handle division by zero and
invalid input errors.

Answer:
try:
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
result = a / b
except ZeroDivisionError:
print("Cannot divide by zero")
except ValueError:
print("Invalid input")
else:
print("Result:", result)
finally:
print("Execution completed")

Question 2:
Write a program that takes a list index from the user and prints the element. Handle invalid index
and non-integer input.

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

try:
index = int(input("Enter index: "))
print("Element:", lst[index])
except IndexError:
print("Index out of range")
except ValueError:
print("Invalid input")

Question 3:
Write a program that opens a file and reads its content. Handle file not found and permission
errors.

Answer:
try:
f = open("[Link]", "r")
content = [Link]()
print(content)
[Link]()
except FileNotFoundError:
print("File not found")
except PermissionError:
print("Permission denied")

Question 4:
Write a program using nested try-except blocks:

 Outer block handles input errors


 Inner block handles division errors

Answer:
try:
a = int(input("Enter number: "))
try:
result = 100 / a
print("Result:", result)
except ZeroDivisionError:
print("Division by zero")
except ValueError:
print("Invalid input")

Question 5:
Write a program that raises a custom exception if a number is negative.

Answer:
class NegativeNumberError(Exception):
pass

try:
num = int(input("Enter number: "))
if num < 0:
raise NegativeNumberError("Negative number not allowed")
print("Number is:", num)
except NegativeNumberError as e:
print(e)

Question 6:
Write a program that uses finally to ensure a file is always closed.
Answer:
try:
f = open("[Link]", "r")
print([Link]())
except FileNotFoundError:
print("File not found")
finally:
try:
[Link]()
except:
pass

Question 7:
Write a program that uses assert to check that a number is greater than 0.

Answer:
try:
num = int(input("Enter number: "))
assert num > 0, "Number must be positive"
print("Valid number")
except AssertionError as e:
print(e)

Question 8:
Write a program that handles multiple exceptions in a single except block.

Answer:
try:
a = int(input("Enter number: "))
b = int(input("Enter number: "))
print(a / b)
except (ValueError, ZeroDivisionError):
print("Error occurred: Invalid input or division by zero")

Question 9:
Write a program that demonstrates use of else block with try-except.

Answer:
try:
num = int(input("Enter number: "))
except ValueError:
print("Invalid input")
else:
print("Square:", num * num)

Question 10:
Write a program that keeps asking user input until a valid integer is entered using exception
handling.

Answer:
while True:
try:
num = int(input("Enter integer: "))
print("You entered:", num)
break
except ValueError:
print("Invalid input, try again")

Strings
Question 1:
Write a program to check whether a string is a palindrome without using slicing [::-1].

Answer:
s = input("Enter string: ")
i=0
j = len(s) - 1
is_palindrome = True

while i < j:
if s[i] != s[j]:
is_palindrome = False
break
i += 1
j -= 1

if is_palindrome:
print("Palindrome")
else:
print("Not Palindrome")
Question 2:
Write a program to count frequency of each character in a string without using collections.

Answer:
s = input("Enter string: ")
visited = []

for ch in s:
if ch not in visited:
count = 0
for c in s:
if c == ch:
count += 1
print(ch, ":", count)
[Link](ch)

Question 3:
Write a program to remove all duplicate characters from a string while preserving order.

Answer:
s = input("Enter string: ")
result = ""

for ch in s:
if ch not in result:
result += ch

print(result)

Question 4:
Write a program to find the first non-repeating character in a string.

Answer:
s = input("Enter string: ")

for ch in s:
if [Link](ch) == 1:
print("First non-repeating character:", ch)
break
else:
print("No unique character")
Question 5:
Write a program to check if two strings are anagrams without using sorted().

Answer:
s1 = input("Enter first string: ")
s2 = input("Enter second string: ")

if len(s1) != len(s2):
print("Not Anagram")
else:
is_anagram = True
for ch in s1:
if [Link](ch) != [Link](ch):
is_anagram = False
break

if is_anagram:
print("Anagram")
else:
print("Not Anagram")

Question 6:
Write a program to find the longest word in a sentence.

Answer:
sentence = input("Enter sentence: ")
words = [Link]()

longest = words[0]

for word in words:


if len(word) > len(longest):
longest = word

print("Longest word:", longest)

Question 7:
Write a program to count vowels, consonants, digits, and special characters in a string.

Answer:
s = input("Enter string: ")
vowels = 0
consonants = 0
digits = 0
special = 0

for ch in s:
if [Link]():
digits += 1
elif [Link]():
if [Link]() in "aeiou":
vowels += 1
else:
consonants += 1
else:
special += 1

print("Vowels:", vowels)
print("Consonants:", consonants)
print("Digits:", digits)
print("Special Characters:", special)

Question 8:
Write a program to check if a string is a rotation of another string.

Answer:
s1 = input("Enter first string: ")
s2 = input("Enter second string: ")

if len(s1) == len(s2) and s2 in (s1 + s1):


print("Rotation")
else:
print("Not Rotation")

Question 9:
Write a program to find the most frequent character in a string.

Answer:
s = input("Enter string: ")

max_char = s[0]
max_count = 0
for ch in s:
count = [Link](ch)
if count > max_count:
max_count = count
max_char = ch

print("Most frequent character:", max_char)

Question 10:
Write a program to reverse each word in a sentence but keep word order same.

Answer:
sentence = input("Enter sentence: ")
words = [Link]()

result = ""

for word in words:


result += word[::-1] + " "

print([Link]())

File Handling
Question 1:
Write a program that reads a text file and counts:

 total number of words


 total number of lines
 total number of characters

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

lines = [Link]()

word_count = 0
char_count = 0

for line in lines:


word_count += len([Link]())
char_count += len(line)

[Link]()
print("Lines:", len(lines))
print("Words:", word_count)
print("Characters:", char_count)

Question 2:
Write a program to copy contents of one file into another file but remove all blank lines.

Answer:
source = open("[Link]", "r")
target = open("[Link]", "w")

for line in source:


if [Link]() != "":
[Link](line)

[Link]()
[Link]()

Question 3:
Write a program that reads a file and finds the frequency of each word.

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

word_freq = {}

for line in file:


words = [Link]()
for word in words:
word = [Link]()
if word in word_freq:
word_freq[word] += 1
else:
word_freq[word] = 1

[Link]()

print(word_freq)
Question 4:
Write a program that searches for a specific word in a file and prints all line numbers where it
appears.

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

search_word = input("Enter word to search: ").lower()

line_no = 0

for line in file:


line_no += 1
if search_word in [Link]():
print("Found at line:", line_no)

[Link]()

Question 5:
Write a program to remove all punctuation marks from a file and save cleaned text into another
file.

Answer:
import string

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


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

for line in file:


for p in [Link]:
line = [Link](p, "")
[Link](line)

[Link]()
[Link]()

Question 6:
Write a program that reads numbers from a file and writes only even numbers into another file.

Answer:
file = open("[Link]", "r")
even_file = open("[Link]", "w")
for line in file:
nums = [Link]()
for num in nums:
if int(num) % 2 == 0:
even_file.write(num + "\n")

[Link]()
even_file.close()

Question 7:
Write a program that appends user input into a file until the user types "STOP".

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

while True:
text = input("Enter text (STOP to end): ")

if text == "STOP":
break

[Link](text + "\n")

[Link]()

Question 8:
Write a program that reads a file and finds the longest word.

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

longest = ""

for line in file:


words = [Link]()
for word in words:
if len(word) > len(longest):
longest = word

[Link]()

print("Longest word:", longest)


Question 9:
Write a program that merges two files into a third file line by line.

Answer:
file1 = open("[Link]", "r")
file2 = open("[Link]", "r")
output = open("[Link]", "w")

lines1 = [Link]()
lines2 = [Link]()

for i in range(max(len(lines1), len(lines2))):


if i < len(lines1):
[Link](lines1[i])
if i < len(lines2):
[Link](lines2[i])

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

Question 10:
Write a program that reads a log file and separates ERROR and INFO messages into different
files.

Answer:
log = open("[Link]", "r")
error_file = open("[Link]", "w")
info_file = open("[Link]", "w")

for line in log:


if "ERROR" in line:
error_file.write(line)
elif "INFO" in line:
info_file.write(line)

[Link]()
error_file.close()
info_file.close()

JSON with Python


Question 1:
Write a program that reads a JSON string and prints all keys and values recursively (including
nested JSON objects).

Answer:
import json

def print_json(data, indent=0):


for key, value in [Link]():
if isinstance(value, dict):
print(" " * indent + str(key) + ":")
print_json(value, indent + 1)
else:
print(" " * indent + str(key) + ":", value)

json_data = '{"name":"Ali","info":{"age":20,"city":"Karachi"}}'
data = [Link](json_data)

print_json(data)

Question 2:
Write a program that counts how many times each key appears in a list of JSON objects.

Answer:
import json

data = [
{"name": "Ali", "age": 20},
{"name": "Sara", "city": "Lahore"},
{"name": "Ahmed", "age": 22}
]

key_count = {}

for obj in data:


for key in obj:
key_count[key] = key_count.get(key, 0) + 1

print(key_count)

Question 3:
Write a program to filter JSON records where salary > 50000.
Answer:
import json

data = [
{"name": "A", "salary": 40000},
{"name": "B", "salary": 60000},
{"name": "C", "salary": 80000}
]

filtered = []

for emp in data:


if emp["salary"] > 50000:
[Link](emp)

print(filtered)

Question 4:
Write a program that loads JSON data and calculates average age from nested JSON structure.

Answer:
import json

data = '''
[
{"name": "A", "info": {"age": 20}},
{"name": "B", "info": {"age": 30}},
{"name": "C", "info": {"age": 40}}
]
'''

records = [Link](data)

total = 0
count = 0

for r in records:
total += r["info"]["age"]
count += 1

print("Average Age:", total / count)


Question 5:
Write a program that merges two JSON arrays based on a common key (id).

Answer:
import json

list1 = [
{"id": 1, "name": "Ali"},
{"id": 2, "name": "Sara"}
]

list2 = [
{"id": 1, "marks": 80},
{"id": 2, "marks": 90}
]

merged = []

for a in list1:
for b in list2:
if a["id"] == b["id"]:
[Link]({**a, **b})

print(merged)

Question 6:
Write a program to find missing keys in JSON objects and replace them with "N/A".

Answer:
import json

data = [
{"name": "Ali", "age": 20},
{"name": "Sara"},
{"age": 25}
]

for obj in data:


if "name" not in obj:
obj["name"] = "N/A"
if "age" not in obj:
obj["age"] = "N/A"

print(data)
Question 7:
Write a program that reads JSON file, modifies values, and writes back to file.

Answer:
import json

data = {"name": "Ali", "salary": 40000}

with open("[Link]", "w") as f:


[Link](data, f)

with open("[Link]", "r") as f:


loaded = [Link](f)

loaded["salary"] += 10000

with open("[Link]", "w") as f:


[Link](loaded, f)

print(loaded)

Question 8:
Write a program that validates JSON structure and handles errors using try-except.

Answer:
import json

json_data = '{"name":"Ali", "age":20,}' # invalid JSON

try:
data = [Link](json_data)
print(data)
except [Link]:
print("Invalid JSON Format")

Question 9:
Write a program that converts a Python dictionary into JSON and formats it with indentation.

Answer:
import json
data = {
"name": "Ali",
"age": 20,
"skills": ["Python", "AI", "ML"]
}

json_string = [Link](data, indent=4)


print(json_string)

Question 10:
Write a program that simulates API response in JSON and extracts only specific fields (name
and salary).

Answer:
import json

response = '''
[
{"name": "Ali", "salary": 50000, "city": "Karachi"},
{"name": "Sara", "salary": 60000, "city": "Lahore"}
]
'''

data = [Link](response)

for emp in data:


print(emp["name"], emp["salary"])

Consuming Apis in python


Question 1:
Write a program that consumes a public API and prints all user names from JSONPlaceholder
API.

Answer:
import requests

url = "[Link]
response = [Link](url)

data = [Link]()

for user in data:


print(user["name"])
Question 2:
Write a program that sends a POST request to an API and creates a new user.

Answer:
import requests

url = "[Link]

payload = {
"title": "Hello",
"body": "This is test data",
"userId": 1
}

response = [Link](url, json=payload)

print([Link]())

Question 3:
Write a program that handles API errors (status codes) properly.

Answer:
import requests

url = "[Link]

response = [Link](url)

if response.status_code == 200:
print("Success")
data = [Link]()
print(data)
else:
print("Error:", response.status_code)

Question 4:
Write a program that fetches data from an API and filters users whose id is greater than 5.

Answer:
import requests
url = "[Link]
response = [Link](url)

data = [Link]()

for user in data:


if user["id"] > 5:
print(user["name"], user["id"])

Question 5:
Write a program that sends request with custom headers.

Answer:
import requests

url = "[Link]

headers = {
"User-Agent": "MyApp/1.0",
"Accept": "application/json"
}

response = [Link](url, headers=headers)

print([Link]())

Question 6:
Write a program that simulates pagination by fetching data in chunks (limit and page).

Answer:
import requests

page = 1

while True:
url = f"[Link]
response = [Link](url)

data = [Link]()

if not data:
break
print(f"Page {page}")

for item in data:


print(item["id"], item["title"])

page += 1

Question 7:
Write a program that extracts nested JSON data from API response (address city of users).

Answer:
import requests

url = "[Link]
response = [Link](url)

data = [Link]()

for user in data:


print(user["name"], "-", user["address"]["city"])

Question 8:
Write a program that retries API request if it fails (basic retry mechanism).

Answer:
import requests
import time

url = "[Link]

for attempt in range(3):


try:
response = [Link](url)

if response.status_code == 200:
print("Success")
print([Link]())
break
else:
print("Failed attempt", attempt + 1)

except:
print("Error occurred")
[Link](2)
Question 9:
Write a program that calculates total number of posts per user from API.

Answer:
import requests

url = "[Link]
response = [Link](url)

data = [Link]()

count = {}

for post in data:


user_id = post["userId"]
count[user_id] = [Link](user_id, 0) + 1

print(count)

Question 10:
Write a program that consumes API and extracts only selected fields (id and title) and stores
them in a new list.

Answer:
import requests

url = "[Link]
response = [Link](url)

data = [Link]()

result = []

for post in data:


[Link]({
"id": post["id"],
"title": post["title"]
})

print(result)

You might also like