0% found this document useful (0 votes)
0 views16 pages

100 Python Practice Solutions

The document contains 100 Python practice questions with complete solutions and explanations, organized into three sections: Basic Programs, Conditional Statements, and Loops. Each question provides a specific programming task along with the corresponding Python code and a brief explanation of the concepts used. This resource is tailored for students in a Computer Science program, aiming to enhance their coding skills through practical exercises.
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)
0 views16 pages

100 Python Practice Solutions

The document contains 100 Python practice questions with complete solutions and explanations, organized into three sections: Basic Programs, Conditional Statements, and Loops. Each question provides a specific programming task along with the corresponding Python code and a brief explanation of the concepts used. This resource is tailored for students in a Computer Science program, aiming to enhance their coding skills through practical exercises.
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

100 Python Practice Questions

Complete Solutions with Explanations

Prepared for: Bankar Siddheshwar Adinath (Siddhu)

Arts, Commerce & Science College, Sonai | SPPU | S.Y. BSc Computer Science
Section 1: Basic Programs (Q1–Q20)
Q1. Print Hello World
print() outputs text to the console. String literals are written in quotes.
print("Hello, World!")

Q2. Add Two Numbers


input() reads user input as a string; int() converts it to integer. Use + for addition.
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print("Sum =", a + b)

Q3. Subtract Two Numbers


Use the - operator for subtraction.
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print("Difference =", a - b)

Q4. Multiply Two Numbers


Use the * operator for multiplication.
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print("Product =", a * b)

Q5. Divide Two Numbers


Use float() for decimal precision. Always check for zero before dividing.
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
if b != 0:
print("Quotient =", a / b)
else:
print("Cannot divide by zero!")

Q6. Find the Remainder


The % (modulo) operator returns the remainder of division.
a = int(input("Enter dividend: "))
b = int(input("Enter divisor: "))
print("Remainder =", a % b)

Q7. Swap Two Numbers


Python allows tuple unpacking for swapping in one line — no temp variable needed.
a = int(input("Enter a: "))
b = int(input("Enter b: "))
a, b = b, a
print("After swap: a =", a, ", b =", b)

Q8. Find Largest of Two


Use if-elif-else to compare two values.
a = int(input("Enter first: "))
b = int(input("Enter second: "))
if a > b:
print(a, "is larger")
elif b > a:
print(b, "is larger")
else:
print("Both are equal")

Q9. Find Largest of Three


max() returns the greatest value among its arguments.
a = int(input("Enter a: "))
b = int(input("Enter b: "))
c = int(input("Enter c: "))
largest = max(a, b, c)
print("Largest =", largest)
Q10. Even or Odd
A number is even if remainder when divided by 2 is 0.
n = int(input("Enter a number: "))
if n % 2 == 0:
print(n, "is Even")
else:
print(n, "is Odd")

Q11. Positive, Negative or Zero


Three conditions cover all cases for a number's sign.
n = float(input("Enter a number: "))
if n > 0:
print("Positive")
elif n < 0:
print("Negative")
else:
print("Zero")

Q12. Square of a Number


The ** operator computes powers. n**2 means n squared.
n = float(input("Enter a number: "))
print("Square =", n ** 2)

Q13. Cube of a Number


n**3 computes the cube of n.
n = float(input("Enter a number: "))
print("Cube =", n ** 3)

Q14. Square Root


[Link]() from the math module computes square root.
import math
n = float(input("Enter a number: "))
print("Square Root =", [Link](n))

Q15. Celsius to Fahrenheit


Formula: F = (C x 9/5) + 32
c = float(input("Enter temperature in Celsius: "))
f = (c * 9/5) + 32
print("Fahrenheit =", f)

Q16. Fahrenheit to Celsius


Formula: C = (F - 32) x 5/9
f = float(input("Enter temperature in Fahrenheit: "))
c = (f - 32) * 5/9
print("Celsius =", c)

Q17. Area of Rectangle


Area of rectangle = length x breadth.
l = float(input("Length: "))
b = float(input("Breadth: "))
print("Area =", l * b)

Q18. Area of Circle


Area = pi * r^2. Use [Link] for the constant pi.
import math
r = float(input("Radius: "))
print("Area =", [Link] * r ** 2)

Q19. Perimeter of Rectangle


Perimeter = 2 x (length + breadth).
l = float(input("Length: "))
b = float(input("Breadth: "))
print("Perimeter =", 2 * (l + b))
Q20. Simple Interest
Formula: SI = (P x R x T) / 100
p = float(input("Principal: "))
r = float(input("Rate (%): "))
t = float(input("Time (years): "))
si = (p * r * t) / 100
print("Simple Interest =", si)
Section 2: Conditional Statements (Q21–Q40)
Q21. Leap Year
Leap year: divisible by 4 but not 100, OR divisible by 400.
year = int(input("Enter year: "))
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(year, "is a Leap Year")
else:
print(year, "is not a Leap Year")

Q22. Greatest of Three


Compare each value against the others using logical AND.
a, b, c = int(input("a: ")), int(input("b: ")), int(input("c: "))
if a >= b and a >= c:
print("Greatest:", a)
elif b >= c:
print("Greatest:", b)
else:
print("Greatest:", c)

Q23. Vowel or Consonant


Check membership in the vowel string using 'in'. Use isalpha() to verify it's a letter.
ch = input("Enter a letter: ").lower()
if ch in 'aeiou':
print(ch, "is a Vowel")
elif [Link]():
print(ch, "is a Consonant")
else:
print("Not a letter")

Q24. Divisible by 5 and 11


Use logical AND to check both conditions simultaneously.
n = int(input("Enter number: "))
if n % 5 == 0 and n % 11 == 0:
print(n, "is divisible by both 5 and 11")
else:
print("Not divisible by both")

Q25. Divisible by 2 and 3


A number divisible by both 2 and 3 is also divisible by 6.
n = int(input("Enter number: "))
if n % 2 == 0 and n % 3 == 0:
print("Divisible by both 2 and 3")
else:
print("Not divisible by both")

Q26. Grade from Marks


elif chain checks ranges from highest to lowest — first match wins.
marks = int(input("Enter marks (0-100): "))
if marks >= 90:
print("Grade: A+")
elif marks >= 75:
print("Grade: A")
elif marks >= 60:
print("Grade: B")
elif marks >= 45:
print("Grade: C")
elif marks >= 35:
print("Grade: D")
else:
print("Grade: F (Fail)")

Q27. Eligible to Vote


In India, voting age is 18. Simple threshold check.
age = int(input("Enter age: "))
if age >= 18:
print("Eligible to vote")
else:
print("Not eligible to vote")

Q28. Multiple of 7
Modulo 7 equals 0 means the number is a multiple of 7.
n = int(input("Enter number: "))
if n % 7 == 0:
print(n, "is a multiple of 7")
else:
print(n, "is NOT a multiple of 7")

Q29. Smallest of Three


min() returns the smallest value among its arguments.
a, b, c = int(input("a: ")), int(input("b: ")), int(input("c: "))
print("Smallest:", min(a, b, c))

Q30. Palindrome Number


n[::-1] reverses the string. A palindrome reads the same forwards and backwards.
n = input("Enter a number: ")
if n == n[::-1]:
print(n, "is a Palindrome")
else:
print(n, "is NOT a Palindrome")

Q31. Armstrong Number


Armstrong number: sum of each digit raised to power of total digits equals the number. E.g., 153 =
1^3+5^3+3^3.
n = int(input("Enter a number: "))
digits = len(str(n))
total = sum(int(d) ** digits for d in str(n))
if total == n:
print(n, "is an Armstrong number")
else:
print(n, "is NOT an Armstrong number")

Q32. Perfect Number


A perfect number equals the sum of its proper divisors (e.g., 6 = 1+2+3).
n = int(input("Enter a number: "))
s = sum(i for i in range(1, n) if n % i == 0)
if s == n:
print(n, "is a Perfect number")
else:
print(n, "is NOT a Perfect number")

Q33. Prime Number


Check divisibility up to sqrt(n) — any factor larger than sqrt(n) pairs with one smaller.
n = int(input("Enter a number: "))
if n < 2:
print(n, "is NOT prime")
else:
prime = True
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
prime = False
break
print(n, "is Prime" if prime else "is NOT Prime")

Q34. Neon Number


Neon number: sum of digits of its square equals itself. E.g., 9: 9^2=81, 8+1=9.
n = int(input("Enter a number: "))
sq = n * n
digit_sum = sum(int(d) for d in str(sq))
if digit_sum == n:
print(n, "is a Neon number")
else:
print(n, "is NOT a Neon number")

Q35. Spy Number


Spy number: sum of digits == product of digits. E.g., 1124: sum=8, product=8.
n = input("Enter a number: ")
digits = [int(d) for d in n]
if sum(digits) == 1:
for d in digits[1:]:
digits[0] *= d
prod = digits[0]
else:
prod = 1
for d in digits:
prod *= d
s = sum(int(d) for d in n)
p = prod
if s == p:
print(n, "is a Spy number")
else:
print(n, "is NOT a Spy number")

Q36. Duck Number


Duck number has at least one zero but not as leading digit. Check from index 1 onwards.
n = input("Enter a number: ")
if '0' in n[1:]:
print(n, "is a Duck number")
else:
print(n, "is NOT a Duck number")

Q37. Uppercase or Lowercase


isupper() and islower() are built-in string methods for case checking.
ch = input("Enter a character: ")
if [Link]():
print("Uppercase")
elif [Link]():
print("Lowercase")
else:
print("Not an alphabet")

Q38. Day of Week (1-7)


Store day names in a list. Access by index (n-1 since lists are 0-indexed).
days = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]
n = int(input("Enter day number (1-7): "))
if 1 <= n <= 7:
print("Day:", days[n-1])
else:
print("Invalid input")

Q39. Simple Calculator using if-elif


Read the operator as a string, then use if-elif to pick the correct operation.
a = float(input("First number: "))
op = input("Operator (+, -, *, /): ")
b = float(input("Second number: "))
if op == '+':
print("Result:", a + b)
elif op == '-':
print("Result:", a - b)
elif op == '*':
print("Result:", a * b)
elif op == '/' and b != 0:
print("Result:", a / b)
else:
print("Invalid operator or division by zero")

Q40. Triangle Validity


Triangle inequality: sum of any two sides must be greater than the third side.
a = float(input("Side a: "))
b = float(input("Side b: "))
c = float(input("Side c: "))
if a + b > c and b + c > a and a + c > b:
print("Valid Triangle")
else:
print("Invalid Triangle")
Section 3: Loops (Q41–Q60)
Q41. Print 1 to 10
range(1, 11) generates numbers 1 through 10. end=' ' prints on same line.
for i in range(1, 11):
print(i, end=' ')

Q42. Print 10 to 1
range(10, 0, -1) counts down from 10 to 1 with step -1.
for i in range(10, 0, -1):
print(i, end=' ')

Q43. Even Numbers 1-100


range(2, 101, 2) generates even numbers: 2, 4, 6, ... 100.
for i in range(2, 101, 2):
print(i, end=' ')

Q44. Odd Numbers 1-100


range(1, 101, 2) generates odd numbers: 1, 3, 5, ... 99.
for i in range(1, 101, 2):
print(i, end=' ')

Q45. Sum of First N Natural Numbers


sum(range(1, n+1)) adds all integers from 1 to n. Or use the formula n*(n+1)/2.
n = int(input("Enter N: "))
total = sum(range(1, n + 1))
print("Sum =", total)
# Also: formula = n*(n+1)//2

Q46. Factorial
Multiply numbers from 1 to n iteratively. 0! and 1! are both 1.
n = int(input("Enter N: "))
fact = 1
for i in range(1, n + 1):
fact *= i
print(f"{n}! =", fact)

Q47. Multiplication Table


f-strings format the output neatly. Loop i from 1 to 10.
n = int(input("Enter number: "))
for i in range(1, 11):
print(f"{n} x {i} = {n*i}")

Q48. Reverse a Number


Convert to string, reverse with slicing [::-1], convert back to int.
n = int(input("Enter number: "))
rev = int(str(n)[::-1])
print("Reversed:", rev)

Q49. Count Digits


len() of the string representation gives digit count. Remove minus sign if negative.
n = input("Enter a number: ")
print("Number of digits:", len([Link]('-', '')))

Q50. Sum of Digits


Generator expression sums each character that is a digit.
n = input("Enter a number: ")
total = sum(int(d) for d in n if [Link]())
print("Sum of digits:", total)

Q51. Product of Digits


Multiply each digit. Use isdigit() to skip signs or spaces.
n = input("Enter a number: ")
product = 1
for d in n:
if [Link]():
product *= int(d)
print("Product of digits:", product)

Q52. Fibonacci Series


Each term is the sum of the previous two. Start with 0 and 1.
n = int(input("How many terms: "))
a, b = 0, 1
for _ in range(n):
print(a, end=' ')
a, b = b, a + b

Q53. Prime Numbers 1-100


Helper function is_prime() checks primality. List comprehension collects all primes.
def is_prime(n):
if n < 2: return False
for i in range(2, int(n**0.5)+1):
if n % i == 0: return False
return True

primes = [n for n in range(2, 101) if is_prime(n)]


print(primes)

Q54. Armstrong Numbers 1-1000


Check each number in range. Armstrong: sum of digits each raised to power of digit count.
for n in range(1, 1001):
digits = len(str(n))
if sum(int(d)**digits for d in str(n)) == n:
print(n, end=' ')

Q55. First N Prime Numbers


Use a while loop and counter to collect exactly N primes.
def is_prime(n):
if n < 2: return False
for i in range(2, int(n**0.5)+1):
if n % i == 0: return False
return True

n, count, num = int(input("How many primes: ")), 0, 2


while count < n:
if is_prime(num):
print(num, end=' ')
count += 1
num += 1

Q56. GCD (Greatest Common Divisor)


[Link]() uses the Euclidean algorithm. GCD is largest number dividing both.
import math
a = int(input("Enter a: "))
b = int(input("Enter b: "))
print("GCD =", [Link](a, b))

Q57. LCM (Least Common Multiple)


Formula: LCM(a,b) = |a*b| / GCD(a,b).
import math
a = int(input("Enter a: "))
b = int(input("Enter b: "))
print("LCM =", abs(a * b) // [Link](a, b))

Q58. Power of a Number


** is Python's exponentiation operator. pow(base, exp) also works.
base = float(input("Base: "))
exp = int(input("Exponent: "))
print(f"{base}^{exp} =", base ** exp)

Q59. Numbers Divisible by 3 and 5


These are multiples of 15. List comprehension with two conditions.
print([n for n in range(1, 101) if n % 3 == 0 and n % 5 == 0])

Q60. Separate Sum of Even and Odd


Two generator expressions compute sums independently in one line each.
n = int(input("Enter N: "))
even_sum = sum(i for i in range(1, n+1) if i % 2 == 0)
odd_sum = sum(i for i in range(1, n+1) if i % 2 != 0)
print("Even sum:", even_sum, " | Odd sum:", odd_sum)
Section 4: Strings (Q61–Q75)
Q61. Length of String
len() returns the number of characters in the string.
s = input("Enter string: ")
print("Length:", len(s))

Q62. Reverse String


Slicing s[::-1] reverses any sequence in Python.
s = input("Enter string: ")
print("Reversed:", s[::-1])

Q63. Palindrome String


Normalize by lowercasing and removing spaces before comparing.
s = input("Enter string: ").lower().replace(' ', '')
if s == s[::-1]:
print("Palindrome")
else:
print("Not a Palindrome")

Q64. Count Vowels


Iterate over each character and check if it's in the vowel set.
s = input("Enter string: ").lower()
count = sum(1 for ch in s if ch in 'aeiou')
print("Vowels:", count)

Q65. Count Consonants


isalpha() ensures only letters are counted. Exclude vowels from the count.
s = input("Enter string: ").lower()
count = sum(1 for ch in s if [Link]() and ch not in 'aeiou')
print("Consonants:", count)

Q66. Count Uppercase/Lowercase


isupper() and islower() check individual character case.
s = input("Enter string: ")
upper = sum(1 for c in s if [Link]())
lower = sum(1 for c in s if [Link]())
print("Uppercase:", upper, " Lowercase:", lower)

Q67. Count Digits in String


isdigit() returns True for numeric characters.
s = input("Enter string: ")
print("Digits:", sum(1 for c in s if [Link]()))

Q68. Remove Spaces


replace(' ', '') removes all space characters from the string.
s = input("Enter string: ")
print("Without spaces:", [Link](' ', ''))

Q69. Replace Word


[Link](old, new) replaces all occurrences of old with new.
s = input("Enter string: ")
old = input("Word to replace: ")
new = input("New word: ")
print([Link](old, new))

Q70. Uppercase
[Link]() converts all characters to uppercase.
s = input("Enter string: ")
print([Link]())

Q71. Lowercase
[Link]() converts all characters to lowercase.
s = input("Enter string: ")
print([Link]())

Q72. Count Character Occurrence


[Link](ch) counts non-overlapping occurrences of ch.
s = input("Enter string: ")
ch = input("Character to count: ")
print(f"'{ch}' appears", [Link](ch), "times")

Q73. Anagram Check


Two strings are anagrams if they contain the same characters. Sorting both and comparing works.
s1 = input("String 1: ").replace(' ', '').lower()
s2 = input("String 2: ").replace(' ', '').lower()
if sorted(s1) == sorted(s2):
print("Anagram")
else:
print("Not Anagram")

Q74. Duplicate Characters


Track seen characters in a set. Add to duplicates if already seen.
s = input("Enter string: ")
seen, dups = set(), set()
for ch in s:
if ch in seen:
[Link](ch)
[Link](ch)
print("Duplicates:", dups if dups else "None")

Q75. Print Each Character


enumerate() gives both index and character in each iteration.
s = input("Enter string: ")
for i, ch in enumerate(s):
print(f"Index {i}: {ch}")
Section 5: Lists, Tuples, Dictionaries & Sets (Q76–Q90)
Q76. Largest in List
map(int, ...) converts each split token to int. max() finds the largest.
lst = list(map(int, input("Enter numbers separated by space: ").split()))
print("Largest:", max(lst))

Q77. Smallest in List


min() returns the smallest element in any iterable.
lst = list(map(int, input("Enter numbers: ").split()))
print("Smallest:", min(lst))

Q78. Sum of List


sum() adds all elements of a list.
lst = list(map(int, input("Enter numbers: ").split()))
print("Sum:", sum(lst))

Q79. Average of List


Average = total sum divided by count of elements.
lst = list(map(int, input("Enter numbers: ").split()))
print("Average:", sum(lst) / len(lst))

Q80. Remove Duplicates


[Link]() removes duplicates while preserving insertion order. set() also works but doesn't
preserve order.
lst = list(map(int, input("Enter numbers: ").split()))
unique = list([Link](lst)) # Preserves order
print("Without duplicates:", unique)

Q81. Sort Ascending


[Link]() sorts in place. sorted(lst) returns a new sorted list.
lst = list(map(int, input("Enter numbers: ").split()))
[Link]()
print("Ascending:", lst)

Q82. Sort Descending


Pass reverse=True to sort() or sorted() for descending order.
lst = list(map(int, input("Enter numbers: ").split()))
[Link](reverse=True)
print("Descending:", lst)

Q83. Merge Lists


The + operator concatenates two lists into one.
list1 = [1, 2, 3]
list2 = [4, 5, 6]
merged = list1 + list2
print("Merged:", merged)

Q84. Frequency of Elements


Counter from collections module counts occurrences of each element.
from collections import Counter
lst = list(map(int, input("Enter numbers: ").split()))
freq = Counter(lst)
for item, count in [Link]():
print(f"{item}: {count} time(s)")

Q85. Search Element


'in' operator checks membership. [Link]() returns first occurrence index.
lst = list(map(int, input("Enter numbers: ").split()))
target = int(input("Search for: "))
if target in lst:
print(f"Found at index {[Link](target)}")
else:
print("Not found")

Q86. Create/Access Tuple


Tuples are immutable sequences. Access by index like lists. Negative index counts from end.
t = (10, 20, 30, 40, 50)
print("Tuple:", t)
print("First element:", t[0])
print("Last element:", t[-1])
print("Slice:", t[1:4])

Q87. Count Tuple Elements


len() gives total count. [Link](x) counts occurrences of x.
t = (1, 2, 3, 2, 1, 4, 2)
print("Total elements:", len(t))
print("Count of 2:", [Link](2))

Q88. Create/Update Dictionary


Dictionary: key-value pairs. Update by assignment, add new key, delete with del.
student = {"name": "Siddhu", "roll": 101, "marks": 85}
print("Before:", student)
student["marks"] = 90 # Update
student["college"] = "Sonai" # Add new
del student["roll"] # Delete
print("After:", student)

Q89. Print Dictionary Keys/Values


keys(), values(), items() return views of the dictionary's keys, values, and pairs.
d = {"a": 1, "b": 2, "c": 3}
print("Keys:", list([Link]()))
print("Values:", list([Link]()))
print("Items:", list([Link]()))

Q90. Union and Intersection of Sets


Sets support | (union), & (intersection), - (difference) operators natively.
A = {1, 2, 3, 4, 5}
B = {3, 4, 5, 6, 7}
print("Union:", A | B)
print("Intersection:", A & B)
print("Difference A-B:", A - B)
Section 6: Functions & File Handling (Q91–Q100)
Q91. Function to Add Numbers
def defines a function. return sends the result back to the caller.
def add(a, b):
return a + b

x = float(input("First: "))
y = float(input("Second: "))
print("Sum:", add(x, y))

Q92. Function for Factorial


Encapsulating logic in a function makes it reusable.
def factorial(n):
result = 1
for i in range(1, n + 1):
result *= i
return result

n = int(input("Enter N: "))
print(f"{n}! =", factorial(n))

Q93. Function to Check Prime


Functions returning True/False (predicates) are useful for filtering and conditionals.
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True

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


print(n, "is Prime" if is_prime(n) else "is NOT Prime")

Q94. Recursive Factorial


Recursion: function calls itself. Base case prevents infinite recursion. n! = n * (n-1)!
def factorial(n):
if n == 0 or n == 1: # Base case
return 1
return n * factorial(n - 1) # Recursive call

n = int(input("Enter N: "))
print(f"{n}! =", factorial(n))

Q95. Read Text File


open() with 'r' mode reads files. 'with' statement auto-closes the file. Handle exceptions.
filename = input("Enter filename: ")
try:
with open(filename, 'r') as f:
content = [Link]()
print(content)
except FileNotFoundError:
print("File not found!")

Q96. Write Text File


'w' mode creates or overwrites the file. Use 'a' mode to append without overwriting.
filename = input("Filename to write: ")
text = input("Enter text: ")
with open(filename, 'w') as f:
[Link](text)
print("Written successfully!")

Q97. Copy File


Read from source, write to destination. For binary files use 'rb' and 'wb' modes.
src = input("Source file: ")
dst = input("Destination file: ")
try:
with open(src, 'r') as f:
data = [Link]()
with open(dst, 'w') as f:
[Link](data)
print("File copied successfully!")
except FileNotFoundError:
print("Source file not found!")

Q98. Count Lines in File


readlines() returns a list where each element is one line of the file.
filename = input("Enter filename: ")
try:
with open(filename, 'r') as f:
lines = [Link]()
print("Total lines:", len(lines))
except FileNotFoundError:
print("File not found!")

Q99. Count Words in File


split() without arguments splits on any whitespace and removes empty strings.
filename = input("Enter filename: ")
try:
with open(filename, 'r') as f:
content = [Link]()
words = [Link]()
print("Total words:", len(words))
except FileNotFoundError:
print("File not found!")

Q100. Student Management System


Combines dictionaries, functions, loops, and user input. A menu-driven program is a common
mini-project pattern.
students = {}

def add_student():
roll = input("Roll No: ")
name = input("Name: ")
marks = float(input("Marks: "))
students[roll] = {"name": name, "marks": marks}
print("Student added!")

def view_students():
if not students:
print("No records found.")
for roll, info in [Link]():
print(f"Roll: {roll} | Name: {info['name']} | Marks: {info['marks']}")

def delete_student():
roll = input("Roll No to delete: ")
if roll in students:
del students[roll]
print("Deleted!")
else:
print("Not found!")

while True:
print("\n1. Add 2. View 3. Delete 4. Exit")
choice = input("Choice: ")
if choice == '1': add_student()
elif choice == '2': view_students()
elif choice == '3': delete_student()
elif choice == '4': break
else: print("Invalid choice")

You might also like