Programing
Programing
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
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: "))
month_names = ["","January","February","March","April","May","June",
"July","August","September","October","November","December"]
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 sq_sum == sq_hyp:
angle_type = "Right"
elif sq_sum > sq_hyp:
angle_type = "Acute"
else:
angle_type = "Obtuse"
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
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}")
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): "))
print(f"Category: {category}")
BMI: 22.9
Category: Normal
Advice: Maintain current diet and exercise.
Question 1 (Easy)
Formula:
Solution:
length = float(input("Enter length: "))
width = float(input("Enter width: "))
print("Area:", area)
print("Perimeter:", perimeter)
👉 Formula:
F = (C × 9/5) + 32
Solution:
celsius = float(input("Enter temperature in Celsius: "))
Question 3 (Medium)
👉 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
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: "))
Question 5 (Hard)
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: "))
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:
Answer:
year = int(input("Enter 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: "))
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: "))
Logical Operators
Question 1:
Write a program that takes a username and password and checks access using logical operators.
Access is granted only if:
Answer:
username = input("Enter username: ")
password = input("Enter password: ")
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: ")
Question 4:
Write a program that determines if a student is eligible for admission. Eligibility criteria:
Answer:
math = int(input("Enter Math marks: "))
physics = int(input("Enter Physics marks: "))
chemistry = int(input("Enter Chemistry marks: "))
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:
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:
Answer:
num = int(input("Enter a number: "))
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:
Answer:
day = int(input("Enter day: "))
month = int(input("Enter month: "))
year = int(input("Enter year: "))
Question 5:
Write a program that takes a list of exactly 3 numbers and uses match-case to:
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:
Answer:
total = 0
while True:
num = int(input("Enter number (0 to stop): "))
if num == 0:
break
if num < 0:
continue
total += num
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
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:
count3 += 1
if num % 5 == 0:
count5 += 1
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
if sum_val == num:
print("Armstrong Number")
else:
print("Not an Armstrong Number")
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")
if choice == 3:
break
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
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: ")))
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
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)
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
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
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()))
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]
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 = {}
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 = []
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 = []
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)
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()))
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()))
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()))
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)
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)
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
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()))
print(result)
Functions
Question 1:
Write a function that accepts variable number of arguments (*args) and returns:
Answer:
def process_numbers(*args):
even_sum = 0
odd_product = 1
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
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
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:
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
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:
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]
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: ")
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
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 = ""
print([Link]())
File Handling
Question 1:
Write a program that reads a text file and counts:
Answer:
file = open("[Link]", "r")
lines = [Link]()
word_count = 0
char_count = 0
[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")
[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 = {}
[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")
line_no = 0
[Link]()
Question 5:
Write a program to remove all punctuation marks from a file and save cleaned text into another
file.
Answer:
import string
[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 = ""
[Link]()
Answer:
file1 = open("[Link]", "r")
file2 = open("[Link]", "r")
output = open("[Link]", "w")
lines1 = [Link]()
lines2 = [Link]()
[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")
[Link]()
error_file.close()
info_file.close()
Answer:
import json
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 = {}
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 = []
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
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}
]
print(data)
Question 7:
Write a program that reads JSON file, modifies values, and writes back to file.
Answer:
import json
loaded["salary"] += 10000
print(loaded)
Question 8:
Write a program that validates JSON structure and handles errors using try-except.
Answer:
import 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"]
}
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)
Answer:
import requests
url = "[Link]
response = [Link](url)
data = [Link]()
Answer:
import requests
url = "[Link]
payload = {
"title": "Hello",
"body": "This is test data",
"userId": 1
}
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]()
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"
}
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}")
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]()
Question 8:
Write a program that retries API request if it fails (basic retry mechanism).
Answer:
import requests
import time
url = "[Link]
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 = {}
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 = []
print(result)