About These Assignments
This page contains 30+ practice assignments covering all while loop topics in Python. Each problem is categorized by topic and difficulty:
π‘ Tip: Try solving each problem on your own first. Click the "Show Solution" button only after you've attempted the problem. This approach will help you learn more effectively.
1. Basic While Loop 8 Questions
i = 1
while i <= 10:
print(i)
i += 1
# Output: 1 2 3 4 5 6 7 8 9 10
Here we start with a counter variable i set to 1. The while loop keeps running as long as i is less than or equal to 10. Inside the loop, we print the current value of i and then increase it by 1. This is the most basic and common way to iterate with a while loop.
n = 5
total = 0
i = 1
while i <= n:
total += i
i += 1
print(f"Sum: {total}")
# Output: Sum: 15
In this problem, we use a variable called total to keep track of the sum. The loop runs from 1 to n, adding each number to total. After the loop finishes, we print the final sum. This is a classic example of accumulation in programming.
i = 2
while i <= 20:
print(i)
i += 2
# Output: 2 4 6 8 10 12 14 16 18 20
Instead of checking every number, we start at 2 and jump by 2 each time. This is more efficient because we directly generate only the even numbers. It shows how you can control the step size in a while loop.
i = 10
while i >= 1:
print(i)
i -= 1
# Output: 10 9 8 7 6 5 4 3 2 1
Here we start at 10 and go backwards. The condition checks if i is greater than or equal to 1. Inside the loop, we decrease i by 1 each time. This shows how while loops can work in reverse order as well.
n = 5
factorial = 1
i = 1
while i <= n:
factorial *= i
i += 1
print(f"Factorial: {factorial}")
# Output: Factorial: 120
Factorial means multiplying all numbers from 1 to n. We start factorial at 1, then multiply it by each number from 1 to n. This shows how while loops can handle mathematical operations step by step.
n = 10
a, b = 0, 1
count = 0
while count < n:
print(a)
a, b = b, a + b
count += 1
# Output: 0 1 1 2 3 5 8 13 21 34
The Fibonacci series starts with 0 and 1, and each next number is the sum of the previous two. We keep track of two numbers (a and b) and update them in each iteration. This is a beautiful example of how a simple loop can generate a complex mathematical sequence.
num = 5
i = 1
while i <= 10:
print(f"{num} x {i} = {num * i}")
i += 1
# Output: 5 x 1 = 5 ... 5 x 10 = 50
This is a practical use case where we generate a multiplication table. The loop runs from 1 to 10, multiplying the given number by each value. This is how many real-world applications generate tables and reports.
num = 153
original = num
sum_of_cubes = 0
while num > 0:
digit = num % 10
sum_of_cubes += digit ** 3
num = num // 10
if original == sum_of_cubes:
print(f"{original} is Armstrong")
else:
print(f"{original} is not Armstrong")
# Output: 153 is Armstrong
This problem demonstrates how to work with digits of a number. We extract each digit using modulo and integer division, then calculate the sum of cubes. The loop continues until all digits are processed. This is a common pattern in number theory problems.
2. Nested While Loop 6 Questions
rows = 5
i = 1
while i <= rows:
j = 1
while j <= i:
print("*", end="")
j += 1
print()
i += 1
# Output:
# *
# **
# ***
# ****
# *****
The outer loop controls the number of rows. For each row, the inner loop prints stars. The number of stars in each row equals the row number. This is a fundamental pattern in programming that helps understand nested loops.
i = 1
while i <= 10:
j = 1
while j <= 10:
print(f"{i} x {j} = {i*j}")
j += 1
print("---")
i += 1
The outer loop goes through numbers 1 to 10, and for each number, the inner loop multiplies it by numbers 1 to 10. This creates complete multiplication tables. It's a great example of how nested loops can generate structured data.
rows = 5
num = 1
i = 1
while i <= rows:
j = 1
while j <= i:
print(num, end=" ")
num += 1
j += 1
print()
i += 1
# Output:
# 1
# 2 3
# 4 5 6
# 7 8 9 10
# 11 12 13 14 15
Floyd's triangle is a right-angled triangular array of natural numbers. We use a variable num that keeps increasing throughout the loops. The number of elements in each row equals the row number. This pattern is often used in programming interviews.
rows = 5
i = 0
while i < rows:
# Print spaces
j = 0
while j < rows - i - 1:
print(" ", end=" ")
j += 1
# Print numbers
num = 1
j = 0
while j <= i:
print(num, end=" ")
num = num * (i - j) // (j + 1)
j += 1
print()
i += 1
# Output: Pascal's triangle pattern
Pascal's triangle is a more complex pattern where each number is the sum of the two numbers above it. The formula num = num * (i - j) // (j + 1) calculates the next number in the row. This demonstrates how nested loops can handle advanced mathematical patterns.
n = 5
# Upper half
i = 1
while i <= n:
j = 1
while j <= n - i:
print(" ", end=" ")
j += 1
j = 1
while j <= 2 * i - 1:
print("*", end=" ")
j += 1
print()
i += 1
# Lower half
i = n - 1
while i >= 1:
j = 1
while j <= n - i:
print(" ", end=" ")
j += 1
j = 1
while j <= 2 * i - 1:
print("*", end=" ")
j += 1
print()
i -= 1
The diamond pattern combines two triangles: one increasing and one decreasing. We first print spaces to center the stars, then print stars. The upper half increases while the lower half decreases. This shows how to create complex patterns with nested loops.
matrix = [[1,2,3], [4,5,6], [7,8,9]]
i = 0
while i < 3:
row_sum = 0
j = 0
while j < 3:
row_sum += matrix[i][j]
j += 1
print(f"Row {i+1} sum: {row_sum}")
i += 1
# Column sums
j = 0
while j < 3:
col_sum = 0
i = 0
while i < 3:
col_sum += matrix[i][j]
i += 1
print(f"Column {j+1} sum: {col_sum}")
j += 1
This is a practical example of processing 2D data. The outer loop goes through rows, and the inner loop processes columns in each row. For column sums, we swap the loops. This is how data scientists and analysts process tabular data.
3. Infinite While Loop 4 Questions
while True:
print("\n1. Add\n2. Subtract\n3. Multiply\n4. Divide\n5. Exit")
choice = int(input("Choose: "))
if choice == 5:
print("Goodbye!")
break
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
if choice == 1:
print(f"Result: {a+b}")
elif choice == 2:
print(f"Result: {a-b}")
elif choice == 3:
print(f"Result: {a*b}")
elif choice == 4:
print(f"Result: {a/b}")
else:
print("Invalid choice")
The while True loop runs forever until we hit the break statement. This creates a menu-driven program where the user can keep performing operations. This pattern is used in almost every interactive application, from games to business software.
balance = 1000
while True:
print("\n1. Balance\n2. Deposit\n3. Withdraw\n4. Exit")
choice = int(input("Choose: "))
if choice == 1:
print(f"Balance: βΉ{balance}")
elif choice == 2:
amt = int(input("Amount: "))
balance += amt
elif choice == 3:
amt = int(input("Amount: "))
if amt <= balance:
balance -= amt
else:
print("Insufficient balance!")
elif choice == 4:
print("Thank you for using ATM!")
break
This simulates a real ATM where users can perform multiple transactions. The loop continues until the user chooses to exit. It demonstrates how to maintain state (balance) across different operations in a program.
import random
target = random.randint(1, 100)
attempts = 0
while True:
guess = int(input("Guess (1-100): "))
attempts += 1
if guess == target:
print(f"Correct! in {attempts} attempts")
break
elif guess < target:
print("Too low!")
else:
print("Too high!")
The game keeps running until the user guesses correctly. This is a common pattern in games where the game loop continues until a win condition is met. The break statement only executes when the correct number is guessed.
data = []
while True:
entry = input("Enter data (or 'done' to stop): ")
if entry.lower() == 'done':
break
data.append(entry)
print(f"Records collected: {len(data)}")
for item in data:
print(f"- {item}")
This is a classic data collection pattern. The loop continues indefinitely until the user enters a specific keyword. This approach is used in many real-world applications like survey forms, data entry systems, and configuration wizards.
4. Real-World Problems 6 Questions
import time
alarm_time = "15:30"
while True:
current = time.strftime("%H:%M")
print(f"Current time: {current}")
if current == alarm_time:
print("β° ALARM! Time to wake up!")
break
time.sleep(60)
This simulates a real clock with an alarm feature. The loop checks the time every minute. When the current time matches the alarm time, the alarm triggers. This is how many real-time monitoring systems work.
while True:
email = input("Enter email: ")
if '@' in email and '.' in email:
print("Valid email!")
break
print("Invalid email! Try again.")
This is a real validation pattern used in web forms. The loop keeps asking until the user enters valid data. This prevents invalid data from entering the system and provides a better user experience.
students = ["Alice", "Bob", "Charlie", "Diana"]
attendance = {}
i = 0
while i < len(students):
status = input(f"Is {students[i]} present? (y/n): ")
if status.lower() == 'y':
attendance[students[i]] = 'Present'
else:
attendance[students[i]] = 'Absent'
i += 1
print("\nAttendance Report:")
for name, status in attendance.items():
print(f"{name}: {status}")
This is a real-world application for teachers. The loop processes each student one by one, marking attendance. After all students are processed, it generates a report. This is how many educational software systems work.
cart = []
total = 0
while True:
item = input("Enter item name (or 'done'): ")
if item.lower() == 'done':
break
price = float(input("Enter price: "))
cart.append((item, price))
total += price
print("\n=== Shopping Cart ===")
for item, price in cart:
print(f"{item}: βΉ{price}")
print(f"Total: βΉ{total}")
This simulates an e-commerce shopping cart. Users can keep adding items until they type 'done'. The system keeps track of all items and the total price. This is the core of any online shopping experience.
n = 50
num = 2
while num <= n:
is_prime = True
i = 2
while i * i <= num:
if num % i == 0:
is_prime = False
break
i += 1
if is_prime:
print(num, end=" ")
num += 1
# Output: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
This is a classic mathematical problem. We use nested loops to check each number for primality. The inner loop only checks up to the square root of the number for efficiency. This is how many encryption and security systems generate prime numbers.
import random
health = 100
while health > 0:
print(f"\nHealth: {health}")
print("1. Explore\n2. Rest\n3. Quit")
choice = input("Choose: ")
if choice == "1":
if random.random() < 0.3:
damage = random.randint(10, 30)
health -= damage
print(f"Monster attacked! -{damage} HP")
else:
gold = random.randint(10, 50)
print(f"Found {gold} gold!")
elif choice == "2":
health = min(100, health + 20)
print("You rested. +20 HP")
elif choice == "3":
print("Game Over!")
break
if health <= 0:
print("You died! Game Over!")
This is a simple game engine where the game loop continues until the player dies or quits. It demonstrates how game states are managed and how randomness adds excitement. This is the foundation of many video games.
5. Practice Challenges 4 Questions
num = 12321
original = num
rev = 0
while num > 0:
digit = num % 10
rev = rev * 10 + digit
num = num // 10
if original == rev:
print(f"{original} is palindrome")
else:
print(f"{original} is not palindrome")
# Output: 12321 is palindrome
This problem tests number manipulation. We reverse the number by extracting digits and building the reverse. If the reversed number equals the original, it's a palindrome. This is a common interview question.
binary = 1011
decimal = 0
power = 0
while binary > 0:
digit = binary % 10
decimal += digit * (2 ** power)
binary = binary // 10
power += 1
print(f"Decimal: {decimal}")
# Output: Decimal: 11
This is a fundamental computer science problem. Each binary digit is processed from right to left, and multiplied by the corresponding power of 2. This is how computers convert binary to decimal internally.
a, b = 48, 18
while b != 0:
temp = b
b = a % b
a = temp
print(f"GCD: {a}")
# Output: GCD: 6
The Euclidean algorithm is one of the oldest algorithms in mathematics. It repeatedly replaces the larger number with the remainder of division. When the remainder becomes 0, the other number is the GCD. This is used in many areas including cryptography.
while True:
pwd = input("Create password: ")
if len(pwd) < 8:
print("Too short! Min 8 chars")
continue
if not any(c.isupper() for c in pwd):
print("Need uppercase letter")
continue
if not any(c.islower() for c in pwd):
print("Need lowercase letter")
continue
if not any(c.isdigit() for c in pwd):
print("Need at least one digit")
continue
print("Password accepted!")
break
This is a real-world security validation pattern. The loop continues until all password requirements are met. Each validation uses continue to skip to the next iteration if any check fails. This is how modern websites enforce password policies.
Try It Yourself!
Use the interactive editor below to test your solutions or write your own code.
WHILE LOOP PRACTICE
========================================
1. NUMBERS 1 TO 10
1 2 3 4 5 6 7 8 9 10
2. SUM OF FIRST 5 NUMBERS
Sum: 15
3. FIBONACCI SERIES (10 terms)
0 1 1 2 3 5 8 13 21 34
β Write your solutions here!
π Related Tutorials
π While Loop
Learn the fundamentals of while loops
π Nested While Loop
Master loops within loops
βΎοΈ Infinite While Loop
Understanding and controlling infinite loops