Reading about loops is one thing. Writing one from a blank screen, in a lab exam or a coding test, is another. These Python loop practice problems with solutions cover the questions that come up again and again in college practicals, placement tests and beginner interviews in India: sums, factorials, primes, Fibonacci, palindromes and more.
The 20 problems go from easy to hard. Try each one yourself for at least 10 minutes before opening the answer. Getting stuck and then seeing the fix teaches you far more than reading the solution first.
What you need first: Python for and while loops, break, continue and pass and Python if, elif and else.
Key terms
- Accumulator: a variable that collects a result as the loop runs, like
total = 0followed bytotal += n. - Digit extraction: getting digits from a number with
% 10(the last digit) and// 10(the number without its last digit). - Divisor: a number that divides another with no remainder. 3 is a divisor of 12 because 12 % 3 is 0.
- Prime number: a whole number above 1 whose only divisors are 1 and itself, like 2, 3, 5 and 7.
Two tricks used in many problems
Digits with % and //. n % 10 gives the last digit of n. n // 10 removes the last digit. Repeat until n is 0 and you've visited every digit:
n = 4821
while n > 0:
print(n % 10, end=" ")
n //= 10
1 2 8 4
Accumulators. Start a variable at a neutral value (0 for sums and counts, 1 for products), then update it on every pass.
Warm-up problems (1 to 6)
1. Sum of the numbers from 1 to 100.
Show the answer
total = 0
for n in range(1, 101):
total += n
print(total)
5050
Check with the formula n(n + 1) ÷ 2: 100 × 101 ÷ 2 = 5050. In real code you'd write sum(range(1, 101)).
2. Print the multiplication table of 9, from 9 × 1 to 9 × 10.
Show the answer
for i in range(1, 11):
print(f"9 x {i} = {9 * i}")
9 x 1 = 9
9 x 2 = 18
9 x 3 = 27
9 x 4 = 36
9 x 5 = 45
9 x 6 = 54
9 x 7 = 63
9 x 8 = 72
9 x 9 = 81
9 x 10 = 90
3. Count the digits in 4821 without turning it into a string.
Show the answer
n = 4821
count = 0
while n > 0:
count += 1
n //= 10
print(count)
4
The shortcut is len(str(4821)), but tests often ban it to check that you know //. This version gives 0 for the number 0; handle that case separately if it matters.
4. Reverse the number 1234 to get 4321.
Show the answer
Take the last digit off n and add it to the end of reversed_n:
n = 1234
reversed_n = 0
while n > 0:
reversed_n = reversed_n * 10 + n % 10
n //= 10
print(reversed_n)
4321
| n | n % 10 | reversed_n |
|---|---|---|
| 1234 | 4 | 4 |
| 123 | 3 | 43 |
| 12 | 2 | 432 |
| 1 | 1 | 4321 |
5. Find the factorial of 6 (6! = 6 × 5 × 4 × 3 × 2 × 1, read "six factorial").
Show the answer
A product starts at 1, not 0, or the answer is always 0:
n = 6
result = 1
for i in range(2, n + 1):
result *= i
print(result)
720
6. Find the sum of the even numbers from 1 to 50.
Show the answer
Step through the even numbers directly with range(2, 51, 2), instead of testing every number:
print(sum(range(2, 51, 2)))
total = 0
for n in range(1, 51):
if n % 2 == 0:
total += n
print(total)
650
650
Medium problems (7 to 14)
7. Write is_prime(n) and test it on 29 and 91.
Show the answer
You only need to test divisors up to the square root of n. If n = a × b, one of a and b is at most √n.
def is_prime(n):
if n < 2:
return False
i = 2
while i * i <= n:
if n % i == 0:
return False
i += 1
return True
print(is_prime(29), is_prime(91))
True False
91 looks prime, but it's 7 × 13. Checking up to √91 (about 9.5) finds the 7.
8. Print all prime numbers up to 50.
Show the answer
Use for ... else: the else runs only when no divisor caused a break.
primes = []
for n in range(2, 51):
for d in range(2, int(n ** 0.5) + 1):
if n % d == 0:
break
else:
primes.append(n)
print(primes)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
9. Print the first 10 Fibonacci numbers (each number is the sum of the two before it: 0, 1, 1, 2, 3...).
Show the answer
a, b = 0, 1
for _ in range(10):
print(a, end=" ")
a, b = b, a + b
0 1 1 2 3 5 8 13 21 34
a, b = b, a + b updates both at once. Writing a = b and then b = a + b on two lines gives the wrong answer, because a has already changed.
10. Check whether 12321 is a palindrome number (it reads the same backwards).
Show the answer
Reverse it as in problem 4 and compare with the original. Keep a copy, because the loop destroys n:
n = 12321
original = n
reversed_n = 0
while n > 0:
reversed_n = reversed_n * 10 + n % 10
n //= 10
print(original == reversed_n)
True
The string version is str(n) == str(n)[::-1].
11. Find all three-digit Armstrong numbers (the sum of the cubes of the digits equals the number, like 153 = 1³ + 5³ + 3³).
Show the answer
for n in range(100, 1000):
total = 0
temp = n
while temp > 0:
total += (temp % 10) ** 3
temp //= 10
if total == n:
print(n, end=" ")
153 370 371 407
Check 371: 27 + 343 + 1 = 371.
12. Find the sum of the digits of 98765.
Show the answer
n = 98765
total = 0
while n > 0:
total += n % 10
n //= 10
print(total)
35
9 + 8 + 7 + 6 + 5 = 35.
13. Find the GCD (greatest common divisor) and LCM (lowest common multiple) of 48 and 18.
Show the answer
Euclid's method: replace (a, b) with (b, a % b) until b is 0. Then a is the GCD. The LCM is a × b ÷ GCD.
a, b = 48, 18
x, y = a, b
while y != 0:
x, y = y, x % y
gcd = x
lcm = a * b // gcd
print(gcd, lcm)
6 144
The steps: (48, 18) → (18, 12) → (12, 6) → (6, 0). Python also has math.gcd and math.lcm.
14. Find the largest number in [34, 78, 12, 95, 60] without using max().
Show the answer
Start with the first item, not 0. With 0, a list of only negative numbers would give the wrong answer.
numbers = [34, 78, 12, 95, 60]
largest = numbers[0]
for n in numbers[1:]:
if n > largest:
largest = n
print(largest)
95
Harder problems (15 to 20)
15. Count the vowels and consonants in "Incredible India".
Show the answer
Lower-case the text first so capital vowels count, and skip anything that isn't a letter:
text = "Incredible India"
vowels = consonants = 0
for ch in text.lower():
if not ch.isalpha():
continue
if ch in "aeiou":
vowels += 1
else:
consonants += 1
print(vowels, consonants)
7 8
16. Find the second largest number in [34, 78, 12, 95, 60] in one loop, without sorting.
Show the answer
Track the top two. When a new number beats the largest, the old largest becomes second:
numbers = [34, 78, 12, 95, 60]
first = second = float("-inf")
for n in numbers:
if n > first:
second = first
first = n
elif first > n > second:
second = n
print(second)
78
float("-inf") is negative infinity, smaller than every number. first > n in the elif stops a repeat of the largest value from becoming second.
17. Find the perfect numbers up to 1000 (a number equal to the sum of its divisors other than itself, like 6 = 1 + 2 + 3).
Show the answer
for n in range(2, 1001):
divisor_sum = 0
for d in range(1, n // 2 + 1):
if n % d == 0:
divisor_sum += d
if divisor_sum == n:
print(n, end=" ")
6 28 496
No divisor other than n itself is bigger than n ÷ 2, so the inner loop stops there.
18. You save ₹10,000 at 7% interest a year, compounded yearly. How many years until it reaches ₹20,000?
Show the answer
You don't know the number of years in advance, so this is a while loop:
amount = 10000
years = 0
while amount < 20000:
amount *= 1.07
years += 1
print(years, round(amount, 2))
11 21048.52
After 10 years it's about ₹19,672, still short, so it takes 11.
19. Remove duplicates from [3, 1, 3, 2, 1, 5] but keep the original order.
Show the answer
Use a set to remember what you've seen; checking a set is fast. See Python sets.
items = [3, 1, 3, 2, 1, 5]
seen = set()
unique = []
for x in items:
if x not in seen:
seen.add(x)
unique.append(x)
print(unique)
[3, 1, 2, 5]
list(set(items)) also removes duplicates, but it doesn't promise to keep the order. list(dict.fromkeys(items)) does keep it.
20. Convert 156 to binary without using bin().
Show the answer
Divide by 2 repeatedly. The remainders, read from last to first, are the binary digits:
n = 156
bits = ""
while n > 0:
bits = str(n % 2) + bits
n //= 2
print(bits)
print(bin(156))
10011100
0b10011100
Check: 128 + 16 + 8 + 4 = 156. Adding each new bit to the front of the string saves reversing it at the end.
Interview questions
Why do you only need to check divisors up to √n when testing for a prime?
If n = a × b and both a and b were bigger than √n, their product would be bigger than n. So any factor pair has one member at most √n. This cuts the work for n = 1,000,000 from about a million checks to about a thousand.
How do you swap two variables in Python without a third variable?
a, b = b, a. Python builds the tuple on the right first, then unpacks it into the names on the left.
What is the time complexity of finding the second largest number in one pass?
O(n): the list is read once and each item gets a fixed number of comparisons. Sorting first would be O(n log n).
Key takeaways
% 10gives the last digit and// 10removes it: the base of every digit problem.- Start sums at 0 and products at 1; start a "largest so far" at the first item, not 0.
- Use
whilewhen you don't know how many passes you need (interest, digits, Euclid's GCD). for ... elseneatly handles "no divisor found" in prime checks.- Check divisors only up to √n, and update related variables together with
a, b = b, a + b.
Frequently asked questions
How many loop problems should I practise before placement tests?
Enough that the patterns here feel automatic: about 30 to 50 problems, spread over a couple of weeks. After that, practise on a judge such as HackerRank or LeetCode's easy problems, where your code is tested on hidden inputs.
Should I use built-in functions like sum() and max() in exams?
In real code, yes, always. In lab exams and some tests, the examiner may want the loop, so learn both versions. When in doubt, ask.
My answer is different from the one here. Is it wrong?
Not necessarily. Most problems have several correct solutions. Check it against the expected output and a few edge cases, like 0, 1, negative numbers and an empty list.
What to learn next
- Start the next module with tuples and unpacking.
- Learn the collection that problem 19 uses in Python sets.
- See how fast these solutions are with Big-O notation.