This page contains 30+ unique practice assignments that cover all loop concepts in Python. Unlike the topic-specific pages, these problems are designed to test your ability to choose the right loop for each situation and combine loop techniques effectively.
š¢ Beginnerš Intermediateš“ Advanced
šÆ Unique Challenge: Each problem is designed to be different from the topic-specific assignments. You'll need to decide which loop type (for, while, or nested) is most appropriate for each scenario.
š” Tip: Try each problem yourself first. Click "Show Solution" only after attempting.
1. For Loop Challenges 5 Questions
šÆ Focus: Iterate over sequences with for loop.
Beginner Q1: Sum of Squares
Calculate the sum of squares of numbers from 1 to n using a for loop.
š” Solution:
n = int(input("Enter n: "))
sum_sq = 0
for i in range(1, n+1):
sum_sq += i ** 2
print(f"Sum of squares: {sum_sq}")
š Explanation: Uses range() to iterate from 1 to n and accumulates squares.
Beginner Q2: Factorial Using For Loop
Calculate the factorial of a number using a for loop.
š” Solution:
n = int(input("Enter n: "))
fact = 1
for i in range(1, n+1):
fact *= i
print(f"{n}! = {fact}")
š Explanation: Iterative factorial calculation using for loop.
Intermediate Q3: List of Prime Numbers
Generate a list of prime numbers up to n using a for loop.
š” Solution:
n = int(input("Enter n: "))
primes = []
for num in range(2, n+1):
is_prime = True
for i in range(2, int(num**0.5)+1):
if num % i == 0:
is_prime = False
break
if is_prime:
primes.append(num)
print(primes)
š Explanation: Uses nested for loop (one for range, one for primality test).
Intermediate Q4: Reverse a String
Reverse a string using a for loop (without slicing).
š” Solution:
text = input("Enter a string: ")
reversed_text = ""
for char in text:
reversed_text = char + reversed_text
print(f"Reversed: {reversed_text}")
š Explanation: Builds reversed string by prepending each character.
Advanced Q5: Custom Range Generator
Create a custom range function that generates numbers from start to end with a step, but only even numbers.
š” Solution:
def even_range(start, end, step=2):
result = []
for i in range(start, end+1, step):
if i % 2 == 0:
result.append(i)
return result
print(even_range(1, 20, 3))
š Explanation: Custom iteration with filtering inside for loop.
2. While Loop Challenges 5 Questions
šÆ Focus: Condition-based iteration with while loop.
Beginner Q6: Countdown Timer
Print a countdown from n to 1 using a while loop.
š” Solution:
n = int(input("Enter n: "))
while n > 0:
print(n)
n -= 1
print("Blast off!")
š Explanation: Decrements n until it reaches 0.
Beginner Q7: Sum Until Zero
Keep asking the user for numbers until they enter 0, then print the sum.
š” Solution:
total = 0
num = None
while num != 0:
num = int(input("Enter a number (0 to stop): "))
total += num
print(f"Total: {total}")
š Explanation: Sentinel-controlled while loop.
Intermediate Q8: Digit Sum
Calculate the sum of digits of a number using a while loop.
š” Solution:
num = int(input("Enter a number: "))
temp = abs(num)
digit_sum = 0
while temp > 0:
digit_sum += temp % 10
temp //= 10
print(f"Sum of digits: {digit_sum}")
š Explanation: Extracts digits using modulo and integer division.
Intermediate Q9: Palindrome Check
Check if a number is a palindrome using a while loop.
š” Solution:
num = int(input("Enter a number: "))
temp = num
reversed_num = 0
while temp > 0:
reversed_num = reversed_num * 10 + temp % 10
temp //= 10
if num == reversed_num:
print("Palindrome")
else:
print("Not a palindrome")
š Explanation: Reverses number digit by digit using while loop.
Advanced Q10: Collatz Sequence
Generate the Collatz sequence for a given number using a while loop until it reaches 1.
š” Solution:
n = int(input("Enter a number: "))
seq = [n]
while n != 1:
if n % 2 == 0:
n //= 2
else:
n = 3 * n + 1
seq.append(n)
print(seq)
š Explanation: Classic while loop with conditional updates.
3. Nested Loops Challenges 5 Questions
šÆ Focus: Loops within loops for multi-dimensional problems.
Beginner Q11: Multiplication Table Grid
Print a 5x5 multiplication table grid using nested loops.
š” Solution:
for i in range(1, 6):
for j in range(1, 6):
print(f"{i*j:4}", end='')
print()
š Explanation: Outer loop for rows, inner loop for columns.
Intermediate Q12: Number Pyramid
Print a number pyramid with 5 rows using nested loops.
š” Solution:
n = 5
for i in range(1, n+1):
for j in range(1, i+1):
print(j, end=' ')
print()
š Explanation: Inner loop prints increasing numbers per row.
Intermediate Q13: Matrix Diagonal Sum
Calculate the sum of the main diagonal of a 3x3 matrix.
š” Solution:
matrix = [[1,2,3],[4,5,6],[7,8,9]]
diag_sum = 0
for i in range(3):
for j in range(3):
if i == j:
diag_sum += matrix[i][j]
print(f"Diagonal sum: {diag_sum}")
š Explanation: Nested loops with conditional for diagonal elements.
Advanced Q14: Multiplication Table with Different Ranges
Print multiplication tables for numbers 1-5, but only even products (skip odd).
š” Solution:
for i in range(1, 6):
print(f"Table of {i}:", end=' ')
for j in range(1, 11):
product = i * j
if product % 2 == 0:
print(product, end=' ')
print()
š Explanation: Nested loops with conditional filtering inside inner loop.
Advanced Q15: Flatten a List
Flatten a nested list (list of lists) into a single list using nested loops.
š” Solution:
nested = [[1,2,3], [4,5,6], [7,8,9,10]]
flat = []
for sublist in nested:
for item in sublist:
flat.append(item)
print(flat)
š Explanation: Nested loops to traverse all levels of nesting.
4. Break & Continue Challenges 5 Questions
šÆ Focus: Loop control statements.
Beginner Q16: Find First Multiple
Find the first number between 1 and 100 that is divisible by 7 and 3.
š” Solution:
for i in range(1, 101):
if i % 7 == 0 and i % 3 == 0:
print(f"First: {i}")
break
š Explanation: Break exits loop when condition is met.
Beginner Q17: Skip Multiples of 3
Print numbers from 1 to 20, but skip multiples of 3.
š” Solution:
for i in range(1, 21):
if i % 3 == 0:
continue
print(i)
š Explanation: Continue skips the rest of the iteration.
Intermediate Q18: Break on Negative
Keep accepting numbers until a negative number is entered, then break.
š” Solution:
while True:
num = int(input("Enter a number (negative to stop): "))
if num < 0:
break
print(f"You entered: {num}")
š Explanation: Infinite while loop with break condition.
Intermediate Q19: Skip Vowels
Print a string without vowels using continue.
š” Solution:
text = "Hello World"
vowels = "aeiouAEIOU"
result = ""
for char in text:
if char in vowels:
continue
result += char
print(result)
š Explanation: Continue skips vowels, builds result without them.
Advanced Q20: Nested Break
Find the first pair of numbers (i, j) where i*j > 50, using nested loops with break.
š” Solution:
found = False
for i in range(1, 11):
for j in range(1, 11):
if i * j > 50:
print(f"First pair: {i} * {j} = {i*j}")
found = True
break
if found:
break
š Explanation: Nested break using a flag variable.
5. Loop Else Challenges 3 Questions
šÆ Focus: Using else with loops.
Intermediate Q21: Check Prime with Else
Check if a number is prime using for-else.
š” Solution:
n = int(input("Enter a number: "))
for i in range(2, int(n**0.5)+1):
if n % i == 0:
print(f"{n} is not prime")
break
else:
print(f"{n} is prime")
š Explanation: Else executes if loop completes without break.
Intermediate Q22: Search with Else
Search for a number in a list. If not found, print "Not found" using else.
š” Solution:
numbers = [5, 12, 7, 23, 9, 18]
target = int(input("Search for: "))
for num in numbers:
if num == target:
print(f"Found: {target}")
break
else:
print(f"{target} not found")
š Explanation: Else executes when the loop completes without break.
Advanced Q23: While-Else with Validation
Validate user input (positive number) using while-else.
š” Solution:
attempts = 3
while attempts > 0:
num = int(input("Enter a positive number: "))
if num > 0:
print(f"Valid input: {num}")
break
attempts -= 1
print(f"Invalid. {attempts} attempts left.")
else:
print("Max attempts reached. Input validation failed.")
š Explanation: While-else executes when condition becomes false naturally.
6. Advanced Loop Challenges 4 Questions
šÆ Focus: Combining all loop concepts.
Advanced Q24: Number Guessing Game
Create a number guessing game where the user has 5 attempts to guess a random number (1-50).
š” Solution:
import random
secret = random.randint(1, 50)
attempts = 5
while attempts > 0:
guess = int(input(f"Guess (1-50), {attempts} left: "))
if guess == secret:
print("Correct! You won!")
break
elif guess < secret:
print("Too low")
else:
print("Too high")
attempts -= 1
else:
print(f"Game over! The number was {secret}")
š Explanation: Combines while loop, if-else, break, and while-else.
Advanced Q25: Pattern with Conditions
Print a pattern where each row has numbers, but skip rows where the row number is even.
š” Solution:
n = 7
for i in range(1, n+1):
if i % 2 == 0:
continue
for j in range(1, i+1):
print(j, end=' ')
print()
š Explanation: Uses continue in outer loop to skip even rows.
Advanced Q26: While-For Mix
Use a while loop to iterate over a list, and a for loop inside to process each element.
š” Solution:
data = ["apple", "banana", "cherry", "date", "elderberry"]
i = 0
while i < len(data):
word = data[i]
for char in word:
print(char, end='-')
print()
i += 1
š Explanation: Demonstrates mixing while and for loops.
Advanced Q27: Loop with Multiple Conditions
Find numbers between 1 and 100 that are divisible by 3, not divisible by 5, and stop when you find 10 such numbers.
š” Solution:
found = []
num = 1
while len(found) < 10 and num <= 100:
if num % 3 == 0 and num % 5 != 0:
found.append(num)
num += 1
print(f"Found: {found}")
š Explanation: Combines multiple conditions and loop control.
Try It Yourself!
Use the interactive editor below to test your solutions or write your own loop code.
Loading Pyodide... 0%
Python Code Editor
======================================== ALL LOOPS PRACTICE ======================================== Sum of squares (1-5): 55 Countdown: 5 4 3 2 1 Blast off! Number Pyramid: 1 1 2 1 2 3 1 2 3 4