Python Questions & Solutions
🔸 1. Variables & Input
Q1: Write a program that takes a user’s name and age, then prints them.
name = input("Enter your name: ")
age = input("Enter your age: ")
print("Your name is", name, "and you are", age, "years old.")
Q2: Create two variables x = 15 and y = 4. Print their sum, difference, multiplication, and division.
x = 15
y=4
print("Sum:", x + y)
print("Difference:", x - y)
print("Product:", x * y)
print("Division:", x / y)
🔸 2. Conditions (if, elif, else)
Q3: Write a program that checks if a number is positive, negative, or zero.
num = int(input("Enter a number: "))
if num > 0:
print("Positive")
elif num < 0:
print("Negative")
else:
print("Zero")
Q4: Ask a user for their age and print whether they are eligible to vote (age ≥ 18).
age = int(input("Enter your age: "))
if age >= 18:
print("You can vote.")
else:
print("You cannot vote.")
🔸 3. Loops (for, while)
Q5: Print numbers from 1 to 10 using a loop.
for i in range(1, 11):
print(i)
Q6: Write a program using a while loop to sum numbers from 1 to 5.
sum = 0
i=1
while i <= 5:
sum += i
i += 1
print("Sum =", sum)
🔸 4. Lists
Q7: Create a list of 5 fruits. Print the first and last fruit.
fruits = ["Apple", "Banana", "Mango", "Orange", "Grapes"]
print("First fruit:", fruits[0])
print("Last fruit:", fruits[-1])
Q8: Create a list of 3 numbers, then add a new number at the end and print the list.
numbers = [10, 20, 30]
[Link](40)
print(numbers)
🔸 5. Functions
Q9: Create a function that prints "Welcome to Python!"
def welcome():
print("Welcome to Python!")
welcome()
Q10: Create a function that takes a number and returns its square.
def square(num):
return num * num
print(square(5))
Q11: Create a function that takes two numbers and returns their sum.
def add(a, b):
return a + b
print(add(3, 7))
🏁 Bonus Challenge
Q12: Write a function that checks if a number is even or odd.
def check(num):
if num % 2 == 0:
return "Even"
else:
return "Odd"
print(check(9))
📌 Want More?
I can provide:
✔ Exercises Only
✔ MCQs
✔ Project tasks for beginners
✔ Questions based on your class level (7, 8, 9, 10, BS, etc.)
👉 Which one do you want next? 😊
You said:
approximately i want 100 questions
ChatGPT said:
Great! I will prepare 100 Python beginner questions with solutions (from simple variables to
functions, lists, loops, etc.).
Before I create the full set, please choose the difficulty level and format you prefer:
🔰 Select Difficulty
Choose ONE:
1. Very Easy (for grades 6–8)
➝ Basics, print statements, simple variables.
2. Easy to Medium (grade 9–12, college beginners)
➝ Variables, conditions, loops, lists, functions.
3. Mixed Beginner + Logic Tasks (BS Students / Adults)
➝ Beginner concepts + small logical problems.
📌 Select Format
Choose ONE:
A. Question + Solutions Together
B. All Questions First, Solutions Later
C. Separate Files:
One file questions
One file solutions
🎯 Choose Output Type
Choose ONE:
📄 Text list
📘 PDF
📗 Word (.docx)
💻 Python file (.py)
❓ Your Choice Example
Reply like this:
Level: 2
Format: A
Type: PDF
Just reply with your choices and I’ll produce the 100-question package for you. 😊
You said:
ChatGPT said:
Great! You selected:
Level: 2 (Easy to Medium – grade 9–12 / college beginners)
I still need two more choices:
📌 Please choose Format
Reply with A, B, or C:
Option Description
A Questions + Solutions together
B All Questions first, Solutions later
C Two separate files (one with questions, one with solutions)
📎 Please choose Output Type
Reply with 1, 2, 3, or 4:
Option Type
1 Text list (chat message)
2 PDF file
3 Word (.docx)
4 Python file (.py)
✔ Example reply:
Format: A
Type: 2
Just reply with your choices 😊
You said:
ChatGPT said:
Great! You selected:
Format: A (Questions + Solutions Together)
Now please choose the Output Type:
Reply with 1, 2, 3, or 4:
Option Output Type
1 Text list (send here in chat)
2 PDF file
3 Word (.docx)
4 Python file (.py)
✏ Reply like this:
Type: 1
Waiting for your selection 😊
You said:
ChatGPT said:
Perfect!
We will provide 100 Python beginner questions + solutions in text (chat) format.
✔ Final Settings Chosen
Level: Easy to Medium (grade 9–12 / college beginners)
Format: Questions + Solutions Together
Type: Text List
⏳ I will now generate:
✔ 100 Questions
✔ Topics: Variables, Input, Output, Operators, Conditions, Loops, Strings, Lists, Tuples, Dictionaries,
Functions
✔ With complete solutions
⚠ Before I begin: How do you want the style of solutions?
Choose One Style:
🔹 Short + Direct (only essential code)
🔸 Detailed + Explained (comments + explanation)
📌 Reply with:
Short
or
Detailed
Example reply:
Short
Waiting for your choice 😊
You said:
detailed
ChatGPT said:
Awesome — below are 100 Easy→Medium Python questions with detailed solutions (code + short
explanation). I grouped them by topic so you can navigate quickly. Feel free to ask for a printable
PDF or a .py file later.
1–10: Variables & Input/Output
1. Print "Hello, World!".
Solution
print("Hello, World!")
Explanation: print() outputs text to the console. Strings are quoted.
2. Assign x = 10, y = 3. Print both values on one line separated by a space.
Solution
x = 10
y=3
print(x, y)
Explanation: print with multiple arguments prints them with spaces by default.
3. Read a name from input and greet the user: Hello, <name>!.
Solution
name = input("Enter your name: ")
print("Hello, " + name + "!")
Explanation: input() returns a string. Use + to concatenate strings.
4. Read two integers and print their sum.
Solution
a = int(input("First integer: "))
b = int(input("Second integer: "))
print("Sum =", a + b)
Explanation: input() returns string; convert with int() before arithmetic.
5. Read float radius and print area of circle (use 3.14159).
Solution
r = float(input("Radius: "))
area = 3.14159 * r * r
print("Area:", area)
Explanation: Use float() for decimal input; area formula πr².
6. Swap two variables a and b using Python tuple unpacking.
Solution
a=5
b = 10
a, b = b, a
print("a =", a, "b =", b)
Explanation: Python supports simultaneous assignment to swap without temp var.
7. Read a number and print it three times as n n n (same line).
Solution
n = input("Enter something: ")
print(n, n, n)
Explanation: print with multiple args prints them separated by spaces.
8. Read an integer and print whether it's even or odd.
Solution
n = int(input("Enter integer: "))
if n % 2 == 0:
print("Even")
else:
print("Odd")
Explanation: % gives remainder; even when remainder 0.
9. Read first name and last name and print full name with capitalized initials.
Solution
first = input("First name: ").strip()
last = input("Last name: ").strip()
full = [Link]() + " " + [Link]()
print("Full name:", full)
Explanation: strip() removes extra spaces, capitalize() makes first letter uppercase.
10. Read a string and print its length.
Solution
s = input("Enter text: ")
print("Length:", len(s))
Explanation: len() returns number of characters.
11–25: Operators & Simple Arithmetic
11. Compute average of three numbers.
Solution
a = float(input("a: "))
b = float(input("b: "))
c = float(input("c: "))
avg = (a + b + c) / 3
print("Average:", avg)
Explanation: Sum then divide by 3. Use float to accept decimals.
12. Convert minutes to hours and minutes (e.g., 130 → 2 hours 10 minutes).
Solution
total = int(input("Minutes: "))
hours = total // 60
minutes = total % 60
print(f"{hours} hours {minutes} minutes")
Explanation: // integer division for hours, % remainder for minutes.
13. Given length and width, print perimeter and area of rectangle.
Solution
l = float(input("Length: "))
w = float(input("Width: "))
perimeter = 2 * (l + w)
area = l * w
print("Perimeter:", perimeter)
print("Area:", area)
Explanation: Basic geometry formulas.
14. Calculate compound interest: A = P * (1 + r/n)^(n*t).
Solution
P = float(input("Principal P: "))
r = float(input("Annual rate (as decimal): "))
n = int(input("Times per year n: "))
t = float(input("Years t: "))
A = P * (1 + r / n) ** (n * t)
print("Amount:", A)
Explanation: ** is power. Ensure r is decimal (e.g., 0.05).
15. Celsius to Fahrenheit conversion.
Solution
c = float(input("Celsius: "))
f = (c * 9/5) + 32
print("Fahrenheit:", f)
Explanation: Standard conversion formula.
16. Fahrenheit to Celsius.
Solution
f = float(input("Fahrenheit: "))
c = (f - 32) * 5/9
print("Celsius:", c)
Explanation: Inverse formula.
17. Calculate factorial of a small positive integer using a loop.
Solution
n = int(input("Enter n (>=0): "))
fact = 1
for i in range(2, n + 1):
fact *= i
print("Factorial:", fact)
Explanation: Multiply numbers from 2 to n.
18. Check if a number is prime (simple trial division).
Solution
n = int(input("Enter integer >=2: "))
if n <= 1:
print("Not prime")
else:
is_prime = True
i=2
while i * i <= n:
if n % i == 0:
is_prime = False
break
i += 1
print("Prime" if is_prime else "Not prime")
Explanation: Check divisors up to √n.
19. Compute GCD of two numbers using Euclid’s algorithm.
Solution
a = int(input("a: "))
b = int(input("b: "))
while b:
a, b = b, a % b
print("GCD:", abs(a))
Explanation: Repeated remainder step; abs handles negatives.
20. Compute LCM of two integers using GCD.
Solution
a = int(input("a: "))
b = int(input("b: "))
def gcd(x, y):
while y:
x, y = y, x % y
return abs(x)
g = gcd(a, b)
lcm = abs(a * b) // g if g != 0 else 0
print("LCM:", lcm)
Explanation: lcm = |a*b| / gcd.
21. Given a 4-digit number, reverse it.
Solution
n = input("4-digit number: ").strip()
rev = n[::-1]
print("Reversed:", rev)
Explanation: String slicing with step -1 reverses string.
22. Sum digits of a positive integer.
Solution
n = int(input("Enter positive integer: "))
s=0
while n > 0:
s += n % 10
n //= 10
print("Sum of digits:", s)
Explanation: Extract last digit with % 10, drop it with // 10.
23. Check Armstrong number for 3-digit number (sum of cubes of digits equals number).
Solution
n = int(input("3-digit number: "))
temp = n
s=0
while temp > 0:
digit = temp % 10
s += digit ** 3
temp //= 10
print("Armstrong" if s == n else "Not Armstrong")
Explanation: For 3-digit Armstrong, cube digits and compare.
24. Compute the sum of first n natural numbers (formula and loop versions).
Solution (formula)
n = int(input("n: "))
sum_formula = n * (n + 1) // 2
print("Sum (formula):", sum_formula)
Explanation: Use arithmetic series formula to be efficient.
25. Read price and discount percent, print discounted price.
Solution
price = float(input("Price: "))
disc = float(input("Discount %: "))
final = price * (1 - disc / 100)
print("Final price:", final)
Explanation: Subtract percentage of price.
26–40: Conditions & Branching
26. Check sign of a number: positive, negative, zero.
Solution
n = float(input("Number: "))
if n > 0:
print("Positive")
elif n < 0:
print("Negative")
else:
print("Zero")
Explanation: elif handles the middle case.
27. Grading system: A (>=90), B (80–89), C (70–79), D (60–69), F (<60).
Solution
score = float(input("Score (0-100): "))
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print("Grade:", grade)
Explanation: Check highest range first to avoid overlap.
28. Find maximum of three numbers.
Solution
a = float(input("a: "))
b = float(input("b: "))
c = float(input("c: "))
mx = a
if b > mx:
mx = b
if c > mx:
mx = c
print("Maximum:", mx)
Explanation: Keep current max and update.
29. Check if a year is leap year (Gregorian rule).
Solution
year = int(input("Year: "))
is_leap = (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
print("Leap year" if is_leap else "Not a leap year")
Explanation: Leap years: divisible by 4 but not by 100 unless divisible by 400.
30. Check if a character is vowel or consonant (English).
Solution
ch = input("Enter a character: ").strip().lower()
if len(ch) != 1 or not [Link]():
print("Please enter a single alphabetic character.")
else:
if ch in "aeiou":
print("Vowel")
else:
print("Consonant")
Explanation: Validate input and test membership in vowel string.
31. Check whether three lengths can form a triangle.
Solution
a = float(input("a: "))
b = float(input("b: "))
c = float(input("c: "))
if a + b > c and a + c > b and b + c > a:
print("Valid triangle")
else:
print("Not a triangle")
Explanation: Triangle inequality must hold for all pairs.
32. Find whether a character is digit, letter, or other.
Solution
ch = input("Char: ")
if [Link]():
print("Digit")
elif [Link]():
print("Letter")
else:
print("Other")
Explanation: Use string methods isdigit() and isalpha().
33. Given temperature, print clothing suggestion (e.g., <0: heavy coat, 0–15: coat, 16–25: light, >25:
t-shirt).
Solution
t = float(input("Temperature (°C): "))
if t < 0:
suggestion = "Wear a heavy coat"
elif t <= 15:
suggestion = "Wear a coat"
elif t <= 25:
suggestion = "Light clothing"
else:
suggestion = "T-shirt is fine"
print(suggestion)
Explanation: Range checks with elif.
34. Check whether an integer is multiple of 3 and 5.
Solution
n = int(input("n: "))
if n % 3 == 0 and n % 5 == 0:
print("Multiple of both 3 and 5")
elif n % 3 == 0:
print("Multiple of 3")
elif n % 5 == 0:
print("Multiple of 5")
else:
print("Neither")
Explanation: Logical and and or patterns manage combinations.
35. Check if two strings are anagrams (case-insensitive, ignore spaces).
Solution
s1 = input("First string: ").replace(" ", "").lower()
s2 = input("Second string: ").replace(" ", "").lower()
if sorted(s1) == sorted(s2):
print("Anagrams")
else:
print("Not anagrams")
Explanation: Sorted characters equal → anagram.
36. Given a 2-digit number, check if both digits are same.
Solution
n = input("2-digit number: ").strip()
if len(n) == 2 and [Link]():
print("Digits are same" if n[0] == n[1] else "Digits are different")
else:
print("Invalid input")
Explanation: Treat as string to compare digits directly.
37. Check if a point (x,y) lies in the first quadrant (both positive).
Solution
x = float(input("x: "))
y = float(input("y: "))
if x > 0 and y > 0:
print("First quadrant")
else:
print("Not in first quadrant")
Explanation: Simple sign checks.
38. Determine if a triangle is equilateral, isosceles, or scalene.
Solution
a = float(input("a: "))
b = float(input("b: "))
c = float(input("c: "))
if not (a + b > c and a + c > b and b + c > a):
print("Not a triangle")
else:
if a == b == c:
print("Equilateral")
elif a == b or b == c or a == c:
print("Isosceles")
else:
print("Scalene")
Explanation: First validate triangle, then compare sides.
39. Check if input year is in 21st century (2001–2100).
Solution
year = int(input("Year: "))
if 2001 <= year <= 2100:
print("21st century")
else:
print("Not 21st century")
Explanation: Range check with chained comparisons.
40. Simple password check: read password and confirm (two inputs), print match or not.
Solution
p1 = input("Enter password: ")
p2 = input("Confirm password: ")
if p1 == p2:
print("Passwords match")
else:
print("Passwords do not match")
Explanation: Use equality == for strings.
41–60: Loops (for & while), sequences, patterns
41. Print numbers 1–20 using a for loop.
Solution
for i in range(1, 21):
print(i)
Explanation: range(1,21) yields 1..20.
42. Print even numbers from 2 to 20.
Solution
for i in range(2, 21, 2):
print(i)
Explanation: range(start, stop, step).
43. Sum numbers from 1 to n using for loop.
Solution
n = int(input("n: "))
total = 0
for i in range(1, n + 1):
total += i
print("Sum:", total)
Explanation: Iterative addition.
44. Print multiplication table of a number n up to 10.
Solution
n = int(input("n: "))
for i in range(1, 11):
print(f"{n} x {i} = {n * i}")
Explanation: Loop multiplies n by 1..10.
45. Print first n Fibonacci numbers (starting 0,1).
Solution
n = int(input("How many Fibonacci numbers? "))
a, b = 0, 1
count = 0
while count < n:
print(a)
a, b = b, a + b
count += 1
Explanation: Iteratively update two vars to generate sequence.
46. Print pattern:
**
***
for n = 3.
Solution
n = int(input("n: "))
for i in range(1, n + 1):
print("*" * i)
Explanation: String repetition * operator prints stars.
47. Print numbers 1–50 but skip multiples of 7.
Solution
for i in range(1, 51):
if i % 7 == 0:
continue
print(i)
Explanation: continue skips current iteration.
48. Read numbers until user enters 0; print sum of entered numbers (excluding 0).
Solution
s=0
while True:
n = float(input("Enter number (0 to stop): "))
if n == 0:
break
s += n
print("Sum:", s)
Explanation: break exits loop when sentinel reached.
49. Count digits in an integer (without converting to string).
Solution
n = abs(int(input("Enter integer: ")))
if n == 0:
print(1)
else:
count = 0
while n > 0:
n //= 10
count += 1
print("Digits:", count)
Explanation: Repeated integer division removes digits.
50. Print the unique numbers from a list (preserve first occurrence).
Solution
lst = [int(x) for x in input("Numbers (space separated): ").split()]
unique = []
for x in lst:
if x not in unique:
[Link](x)
print("Unique:", unique)
Explanation: Build new list and check membership to avoid repeats.
51. Reverse a list without using .reverse() or reversed().
Solution
lst = [1, 2, 3, 4]
rev = []
for x in lst:
rev = [x] + rev # prepend
print(rev)
Explanation: Prepending builds reversed list; O(n²) for lists but fine for small sizes.
52. Find max in a list using loop (no max() builtin).
Solution
lst = [3, 7, 2, 9, 4]
mx = lst[0]
for x in lst[1:]:
if x > mx:
mx = x
print("Max:", mx)
Explanation: Track the current maximum and update.
53. Count frequency of each character in a string.
Solution
s = input("String: ")
freq = {}
for ch in s:
freq[ch] = [Link](ch, 0) + 1
print("Frequencies:", freq)
Explanation: Use a dictionary and get() default value.
54. Print prime numbers between 2 and n.
Solution
n = int(input("n >= 2: "))
for num in range(2, n + 1):
is_prime = True
i=2
while i * i <= num:
if num % i == 0:
is_prime = False
break
i += 1
if is_prime:
print(num)
Explanation: Check primes individually using sqrt bound.
55. Flatten a 2D list (list of lists) into a single list.
Solution
matrix = [[1,2],[3,4],[5]]
flat = []
for row in matrix:
for item in row:
[Link](item)
print(flat)
Explanation: Nested loops append each element.
56. Read n numbers and print number of positive, negative, and zeros.
Solution
n = int(input("How many numbers: "))
pos = neg = zeros = 0
for _ in range(n):
x = float(input("Number: "))
if x > 0:
pos += 1
elif x < 0:
neg += 1
else:
zeros += 1
print("Positive:", pos, "Negative:", neg, "Zeros:", zeros)
Explanation: Simple counters.
57. Print cumulative sums of a list [1,2,3] → [1,3,6].
Solution
lst = [1, 2, 3, 4]
cum = []
running = 0
for x in lst:
running += x
[Link](running)
print(cum)
Explanation: Keep running total and append.
58. Remove duplicates from a list (order not important) using a set.
Solution
lst = [1, 2, 2, 3, 1]
unique = list(set(lst))
print(unique)
Explanation: set removes duplicates but does not preserve order.
59. Implement while loop to print n asterisks on one line.
Solution
n = int(input("n: "))
i=0
s = ""
while i < n:
s += "*"
i += 1
print(s)
Explanation: Build string via repetition; * * n would be shorter but this shows while loop.
60. Use nested loops to print multiplication table from 1 to 5.
Solution
for i in range(1, 6):
for j in range(1, 6):
print(f"{i*j:3}", end=" ")
print()
Explanation: Nested loops; end=" " avoids newline; formatting aligns columns.
61–80: Strings (manipulation & parsing)
61. Convert a sentence to title case (capitalize each word).
Solution
s = input("Sentence: ")
print([Link]())
Explanation: title() capitalizes words; simple and fast.
62. Check if a string is palindrome (ignore case and spaces).
Solution
s = input("Text: ").replace(" ", "").lower()
if s == s[::-1]:
print("Palindrome")
else:
print("Not palindrome")
Explanation: Normalize then compare with reverse.
63. Find first occurrence of substring "ab" in a string and print index or -1.
Solution
s = input("String: ")
print([Link]("ab"))
Explanation: find() returns first index or -1 if not present.
64. Replace all spaces in a string with underscores.
Solution
s = input("String: ")
print([Link](" ", "_"))
Explanation: replace() swaps substrings.
65. Count words in a sentence (simple split by whitespace).
Solution
s = input("Sentence: ").strip()
words = [Link]()
print("Word count:", len(words))
Explanation: split() defaults to whitespace and collapses multiple spaces.
66. Extract file extension from filename (e.g. [Link] → pdf).
Solution
filename = input("Filename: ").strip()
if "." in filename:
ext = [Link](".")[-1]
print("Extension:", ext)
else:
print("No extension")
Explanation: Splitting by . and taking last piece gives extension.
67. Capitalize first letter of each sentence (assuming . separates sentences).
Solution
text = input("Text: ")
sentences = [Link](". ")
sentences = [[Link]() for s in sentences]
print(". ".join(sentences))
Explanation: Split, apply capitalize() to each, then join back.
68. Remove vowels from a string.
Solution
s = input("String: ")
result = "".join(ch for ch in s if [Link]() not in "aeiou")
print(result)
Explanation: Use comprehension and join() to filter characters.
69. Find all indices of a character in a string.
Solution
s = input("String: ")
ch = input("Character: ")
indices = [i for i, c in enumerate(s) if c == ch]
print(indices)
Explanation: enumerate() gives index and char; comprehension collects matching indices.
70. Count occurrences of each word (case-insensitive).
Solution
s = input("Text: ").lower()
words = [Link]()
freq = {}
for w in words:
freq[w] = [Link](w, 0) + 1
print(freq)
Explanation: Normalize case, split, then dictionary counting.
71. Check if string contains only digits.
Solution
s = input("String: ")
print("Only digits" if [Link]() else "Contains non-digits")
Explanation: isdigit() checks all characters are digits and string not empty.
72. Pad a number with zeros to 5 digits (e.g., 42 → 00042).
Solution
n = int(input("Number: "))
print(str(n).zfill(5))
Explanation: zfill pads left with zeros to desired length.
73. Swap first and last character of a string (if length >= 2).
Solution
s = input("String: ")
if len(s) < 2:
print(s)
else:
s = s[-1] + s[1:-1] + s[0]
print(s)
Explanation: Rebuild string with swapped ends.
74. Split comma-separated numbers and compute their average.
Solution
s = input("Numbers (comma separated): ")
nums = [float(x) for x in [Link](",") if [Link]() != ""]
avg = sum(nums) / len(nums) if nums else 0
print("Average:", avg)
Explanation: Split, convert to floats, handle empty input.
75. Check string contains both letters and digits.
Solution
s = input("String: ")
has_alpha = any([Link]() for ch in s)
has_digit = any([Link]() for ch in s)
print("Has letters and digits" if has_alpha and has_digit else "Does not")
Explanation: any() stops early when condition met.
76. Convert snake_case to camelCase (my_variable → myVariable).
Solution
s = input("snake_case: ")
parts = [Link]("_")
camel = parts[0] + "".join([Link]() for p in parts[1:])
print(camel)
Explanation: First part stays lowercase; subsequent parts capitalized.
77. Find longest word in a sentence.
Solution
s = input("Sentence: ").split()
longest = max(s, key=len) if s else ""
print("Longest word:", longest)
Explanation: max with key=len finds longest item.
78. Remove duplicate words and preserve order.
Solution
s = input("Sentence: ").split()
seen = set()
result = []
for w in s:
if w not in seen:
[Link](w)
[Link](w)
print("Result:", " ".join(result))
Explanation: Use set to test seen words and list to preserve order.
79. Check if two strings differ only in case (i.e., same ignoring case).
Solution
a = input("First: ")
b = input("Second: ")
print("Same ignoring case" if [Link]() == [Link]() else "Different")
Explanation: Lower both and compare.
80. Extract numbers from a string like "a1b2c3" → [1,2,3].
Solution
s = input("String: ")
nums = [int(ch) for ch in s if [Link]()]
print(nums)
Explanation: Filter digits and convert to ints.
81–95: Lists, Tuples, Dictionaries & Comprehensions
81. Sum elements of a list using sum().
Solution
lst = [1, 2, 3, 4]
print("Sum:", sum(lst))
Explanation: Built-in sum is simple and efficient.
82. Create list of squares for numbers 1–10 using list comprehension.
Solution
squares = [i*i for i in range(1, 11)]
print(squares)
Explanation: Comprehensions are concise and readable.
83. Filter even numbers from a list.
Solution
lst = [1, 2, 3, 4, 5, 6]
evens = [x for x in lst if x % 2 == 0]
print(evens)
Explanation: Conditional comprehension filters items.
84. Merge two lists element-wise into list of tuples.
Solution
a = [1, 2, 3]
b = ['a', 'b', 'c']
merged = list(zip(a, b))
print(merged)
Explanation: zip pairs elements; list() makes a list of tuples.
85. Convert two lists keys and values to a dictionary.
Solution
keys = ['a', 'b', 'c']
values = [1, 2, 3]
d = dict(zip(keys, values))
print(d)
Explanation: zip + dict makes a mapping.
86. In a list of dictionaries, find dictionary with max value for a key.
Solution
students = [{"name":"Ali","score":80},{"name":"Zara","score":92}]
top = max(students, key=lambda s: s["score"])
print(top)
Explanation: max with key picks dict with largest score.
87. Reverse keys and values of a dictionary (values unique).
Solution
d = {"a":1,"b":2}
inv = {v:k for k,v in [Link]()}
print(inv)
Explanation: Dict comprehension swaps items.
88. Count how many lists of lengths [len(lst) for lst in list_of_lists] using comprehension.
Solution
list_of_lists = [[1,2],[3],[4,5,6]]
lengths = [len(lst) for lst in list_of_lists]
print(lengths)
Explanation: Comprehension applied to nested lists.
89. Flatten nested list using comprehension (single level).
Solution
matrix = [[1,2],[3,4],[5]]
flat = [x for row in matrix for x in row]
print(flat)
Explanation: Double for in comprehension flattens one level.
90. Group words by their starting letter into a dictionary.
Solution
words = ["apple", "ant", "ball", "bat"]
groups = {}
for w in words:
key = w[0]
[Link](key, []).append(w)
print(groups)
Explanation: setdefault simplifies grouping into lists.
91. Remove None values from a list.
Solution
lst = [1, None, 2, None, 3]
filtered = [x for x in lst if x is not None]
print(filtered)
Explanation: Use is not None because == may differ for falsy values.
92. Rotate a list right by k positions.
Solution
lst = [1,2,3,4,5]
k = int(input("k: ")) % len(lst)
rotated = lst[-k:] + lst[:-k] if k else lst[:]
print(rotated)
Explanation: Use slicing with modulo to handle k > len.
93. Create dictionary counting lengths of words in a list.
Solution
words = ["hi","hello","bye"]
lengths = {w: len(w) for w in words}
print(lengths)
Explanation: Dict comprehension maps word to its length.
94. Find second largest unique number in a list.
Solution
lst = [4, 1, 6, 6, 3]
unique = sorted(set(lst), reverse=True)
second = unique[1] if len(unique) >= 2 else None
print("Second largest:", second)
Explanation: Use set to remove duplicates, sort descending.
95. Merge two dictionaries (Python 3.9+ using | operator; show compatible way too).
Solution
d1 = {"a":1}
d2 = {"b":2}
merged = {**d1, **d2} # compatible
print(merged)
# Python 3.9+: merged = d1 | d2
Explanation: Unpack dictionaries into new dict or use | in modern Python.
96–100: Functions, Modules & Small Projects
96. Write function is_palindrome(s) that returns True/False.
Solution
def is_palindrome(s):
s = ''.join([Link]() for ch in s if [Link]())
return s == s[::-1]
print(is_palindrome("A man, a plan, a canal: Panama"))
Explanation: Normalize by keeping alphanumeric, lowercase; compare with reverse.
97. Write function fibonacci(n) that returns list of first n Fibonacci numbers.
Solution
def fibonacci(n):
result = []
a, b = 0, 1
for _ in range(n):
[Link](a)
a, b = b, a + b
return result
print(fibonacci(7))
Explanation: Returns list; loop n times.
98. Write a function factorial(n) recursively.
Solution
def factorial(n):
if n < 0:
raise ValueError("Negative not allowed")
if n == 0 or n == 1:
return 1
return n * factorial(n - 1)
print(factorial(5))
Explanation: Base case at 0/1; recursion multiplies downwards.
99. Function that returns a dictionary with counts of vowels in a string.
Solution
def vowel_counts(s):
s = [Link]()
counts = {v: 0 for v in "aeiou"}
for ch in s:
if ch in counts:
counts[ch] += 1
return counts
print(vowel_counts("Hello World"))
Explanation: Initialize counts then iterate to increment.
100. Mini-project: Simple todo list CLI with functions to add, view, and remove tasks (in-memory).
Solution
def show_menu():
print("\n1. Add task\n2. View tasks\n3. Remove task\n4. Exit")
def add_task(tasks):
task = input("Task: ").strip()
if task:
[Link](task)
print("Added.")
else:
print("Empty task not added.")
def view_tasks(tasks):
if not tasks:
print("No tasks.")
else:
for i, t in enumerate(tasks, 1):
print(f"{i}. {t}")
def remove_task(tasks):
view_tasks(tasks)
if tasks:
idx = int(input("Remove which number? "))
if 1 <= idx <= len(tasks):
removed = [Link](idx - 1)
print("Removed:", removed)
else:
print("Invalid number.")
def main():
tasks = []
while True:
show_menu()
choice = input("Choice: ").strip()
if choice == "1":
add_task(tasks)
elif choice == "2":
view_tasks(tasks)
elif choice == "3":
remove_task(tasks)
elif choice == "4":
print("Goodbye!")
break
else:
print("Invalid choice.")
if __name__ == "__main__":
main()
Explanation: Small interactive loop storing tasks in a list; functions keep code organized.