Python

P
PythonHub
Progress 0%

Python

  • Home
  • History of Python
  • Applications of Python
  • Introduction To Python
    • What is Python
    • Character Set
    • Tokens in Python
    • Python Execution Mode
    • Variable And Identifiers
    • Data Types in Python
    • Operators And Expressions
    • Constants in Python
    • Assignment Statement
    • Input / Output in Python
    • Simple Python Scripts
    • Namespace in Python
    • πŸ“ Assignments
  • Operators in Python
    • Arithmetic Operators
    • Assignment Operators
    • Shorthand Assignment Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Special Operators
    • πŸ“ Assignments
  • Input Output in Python
    • Accept Input
    • Output Formatting
    • πŸ“ Assignments
  • Conditional Statement
    • Decision Making
    • if Statement
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • Short Hand IF-ELSE
    • πŸ“ Assignments
  • Loops
    • Introduction to Loops
    • While Loop
    • Nested While Loop
    • πŸ“ While Loop Assignments
    • For Loop
    • For Loop Examples
    • Nested For Loop
    • Nested For Loop Examples
    • Infinite While Loops
    • Infinite For Loops
    • Break, Continue and Else in Loops
    • Difference Between For and While Loop
    • For Each Loop
    • πŸ“ For Each Assignments
    • πŸ“ All Loops Assignments
  • List
    • List in Python
    • Access List Elements
    • List Functions
    • Iterate (Loop) List
    • List Comprehension
    • πŸ“ Assignments
  • Tuple
    • Tuple in Python
    • Access Tuple Elements
    • Tuple Functions
    • Iterate (Loop) Tuple
    • Unpack Tuple
    • Tuple Comprehension
    • πŸ“ Assignments
  • Set
    • Set in Python
    • Access Set Elements
    • Set Methods
    • Iterate (Loop) Set
    • Pack/Unpack Set
    • Set Comprehension
    • πŸ“ Assignments
  • Dictionary
    • Dictionary
    • Access Dictionary Items
    • Dictionary Methods
    • Iterate (Loop) Dictionary
    • Formatting Dictionaries
    • Nested Dictionaries
    • Dictionary Comprehension
    • πŸ“ Assignments
  • Diff List Tuple Set Dictionary
    • List vs Tuple
    • List vs Set
    • List vs Dictionary
    • Tuple vs Set
    • Tuple vs Dictionary
    • Dictionary vs Set
    • πŸ“ Assignments
  • Exception
    • Error vs Exception
    • Exception Handling
    • Types of Exception
    • User Defined Exception
    • Logging Exception
    • πŸ“ Assignments
  • Functions
    • Introduction to Functions
    • Modular Programming
    • Types of Functions
    • Inbuilt Functions
    • Need For User-Defined Function
    • Elements of User Defined Function
    • Function Arguments
    • Nesting of Functions
    • Recursion
    • Global Local and Non Local
    • Python Lambda Functions
    • πŸ“ Assignments
  • Python Module
    • Introduction to Module
    • Inbuilt Modules in Python
    • User Defined Module
    • πŸ“ Assignments
  • File Handling
    • Introduction to Files
    • Create File
    • Read Files
    • Write to File
    • Rename File
    • Copy File
    • Move File
    • List Files in Directory
    • Binary Files
    • Zipping and Unzipping Files
    • πŸ“ Assignments
  • Strings
    • Basics of Strings
    • String Special Operators
    • String Formatting Operators
    • String Methods
    • πŸ“ Assignments
  • Regular Expressions
  • Python OOPS
    • Basics of Object Oriented
    • What are Classes and Objects?
    • Creating Class and Object
    • OOP vs Procedural Programming
    • Difference Between Classes and Objects
    • Constructors
    • Destructor
    • Built Class Methods and Attributes
    • Class and Instance Variables
    • Inheritance in Python
    • Single Inheritance
    • Multiple Inheritance
    • Multilevel Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance
    • Abstraction
    • Method Overriding
    • Abstract Method
    • Interfaces in Python
    • Abstract Class vs Interface
    • Public, Private and Protected
    • Overloading vs Overriding
    • Inheritance vs Composition
    • Encapsulation
    • Polymorphism
    • Inner Classes
    • πŸ“ Assignments
  • Advanced Python
    • Iterator in Python
    • Generator in Python
    • Decorator in Python
    • Type Hints in Python
    • Async/Await Programming
    • Dataclasses in Python
    • Context Managers in Python
    • Property Decorator in Python
    • __slots__ in Python
    • Enums in Python
    • Walrus Operator in Python
    • Match-Case in Python
    • πŸ“ Assignments
  • Python Standard Library
    • Collections Module
    • Itertools Module
    • Functools Module
    • Datetime Module
    • JSON Module
    • OS Module
    • Sys Module
    • Random Module
    • Math Module
    • πŸ“ Assignments
  • Python Testing
    • Unit Testing in Python
    • Pytest Framework
    • Mocking in Python
    • πŸ“ Assignments
  • Python Best Practices
    • PEP 8 Style Guide
    • Docstrings in Python
    • Logging in Python
    • Code Optimization Tips
    • Debugging Techniques
    • πŸ“ Assignments
  • MySQL Database in Python
    • Introduction to MySQL with Python
    • DBMS vs File System
    • Connecting to MySQL Database
    • Create Database in MySQL
    • Create Table in MySQL
    • Insert Data in MySQL
    • Insert Multiple Rows
    • Select Data from MySQL
    • WHERE Clause in MySQL
    • Update Data in MySQL
    • Delete Data from MySQL
    • Parameterized Queries
    • Transaction Management
    • Error Handling
    • Connection Pooling
    • MySQL Drivers Guide
    • Joins in MySQL
    • Aggregation Functions
    • Backup MySQL Database
    • Best Practices
    • πŸ“ Assignments
  • MySQL Database Operations
    • SELECT Statement
    • MySQL Operators
    • DDL Statements
    • DML Statements
    • Subqueries
    • JOIN Operations
    • Aggregation
    • Case Study
    • πŸ“ Assignments
  • Graphics in Python
  • Threads in Python
    • Introduction to Threads
    • Process vs Threads
    • Concurrent Programming & GIL
    • Uses of Threads
    • Creating Threads
    • Single Tasking
    • Multi Tasking
    • Thread Synchronization
    • πŸ“ Assignments
  • Interview Questions & Answers
  • Python Case Studies
  • Multiple Choice Questions
  • πŸ“ Practice Problems
Get in Touch
  • tech2dsm@gmail.com

© Sankalan Data Tech

Python Language Interactive Tutorial

πŸ“ Python While Loop: Practice Assignments

Python While Loop Practice Assignments

Master while loops with these hands-on practice assignments.

Created by Sankalan Data Tech Team Verified
Data Engineers, Analysts, Scientists & Trainers
Created by experienced Python developers, data engineers, and data scientists to make programming easy through practical examples, real-world experience, and clear explanations.
πŸ“‘ On this page:
  • About These Assignments
  • Basic While Loop
  • Nested While Loop
  • Infinite While Loop
  • Real-World Problems
  • Try It Yourself
Share this tutorial:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link

About These Assignments

This page contains 30+ practice assignments covering all while loop topics in Python. Each problem is categorized by topic and difficulty:

🟒 Beginner 🟠 Intermediate πŸ”΄ Advanced

πŸ’‘ 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

🎯 Learning Goal: Master the fundamentals of while loops β€” iteration, counters, and basic patterns.
Beginner Basic While Q1: Print numbers 1 to 10
Scenario: Write a while loop that prints numbers from 1 to 10.
πŸ’‘ Solution:
i = 1
while i <= 10:
    print(i)
    i += 1
# Output: 1 2 3 4 5 6 7 8 9 10
πŸ“– Explanation:

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.

Beginner Basic While Q2: Sum of first N natural numbers
Scenario: Calculate the sum of first N natural numbers using while loop.
πŸ’‘ Solution:
n = 5
total = 0
i = 1
while i <= n:
    total += i
    i += 1
print(f"Sum: {total}")
# Output: Sum: 15
πŸ“– Explanation:

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.

Beginner Basic While Q3: Print even numbers up to 20
Scenario: Print all even numbers between 1 and 20 using while loop.
πŸ’‘ Solution:
i = 2
while i <= 20:
    print(i)
    i += 2
# Output: 2 4 6 8 10 12 14 16 18 20
πŸ“– Explanation:

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.

Beginner Basic While Q4: Print numbers in reverse from 10 to 1
Scenario: Write a while loop that prints numbers from 10 down to 1.
πŸ’‘ Solution:
i = 10
while i >= 1:
    print(i)
    i -= 1
# Output: 10 9 8 7 6 5 4 3 2 1
πŸ“– Explanation:

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.

Intermediate Basic While Q5: Factorial of a number
Scenario: Calculate the factorial of a given number using while loop.
πŸ’‘ Solution:
n = 5
factorial = 1
i = 1
while i <= n:
    factorial *= i
    i += 1
print(f"Factorial: {factorial}")
# Output: Factorial: 120
πŸ“– Explanation:

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.

Intermediate Basic While Q6: Fibonacci series up to N terms
Scenario: Generate Fibonacci series up to N terms using while loop.
πŸ’‘ Solution:
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
πŸ“– Explanation:

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.

Intermediate Basic While Q7: Multiplication table generator
Scenario: Generate multiplication table for a given number using while loop.
πŸ’‘ Solution:
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
πŸ“– Explanation:

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.

Advanced Basic While Q8: Armstrong number checker
Scenario: Check if a number is an Armstrong number (sum of cubes of digits equals the number).
πŸ’‘ Solution:
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
πŸ“– Explanation:

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

🎯 Learning Goal: Master nested while loops β€” loops within loops for complex patterns and multi-dimensional data.
Intermediate Nested While Q9: Star pattern (right triangle)
Scenario: Generate a right triangle star pattern using nested while loops.
πŸ’‘ Solution:
rows = 5
i = 1
while i <= rows:
    j = 1
    while j <= i:
        print("*", end="")
        j += 1
    print()
    i += 1
# Output:
# *
# **
# ***
# ****
# *****
πŸ“– Explanation:

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.

Intermediate Nested While Q10: Multiplication table 1 to 10
Scenario: Generate multiplication tables from 1 to 10 using nested while loops.
πŸ’‘ Solution:
i = 1
while i <= 10:
    j = 1
    while j <= 10:
        print(f"{i} x {j} = {i*j}")
        j += 1
    print("---")
    i += 1
πŸ“– Explanation:

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.

Intermediate Nested While Q11: Floyd's triangle
Scenario: Generate Floyd's triangle (consecutive numbers) using nested while loops.
πŸ’‘ Solution:
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
πŸ“– Explanation:

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.

Advanced Nested While Q12: Pascal's triangle
Scenario: Generate Pascal's triangle up to N rows using nested while loops.
πŸ’‘ Solution:
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
πŸ“– Explanation:

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.

Advanced Nested While Q13: Diamond pattern
Scenario: Generate a diamond pattern using nested while loops.
πŸ’‘ Solution:
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
πŸ“– Explanation:

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.

Advanced Nested While Q14: Matrix operations using nested loops
Scenario: Create a 3x3 matrix and calculate sum of each row and column using nested while loops.
πŸ’‘ Solution:
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
πŸ“– Explanation:

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

🎯 Learning Goal: Understand and control infinite while loops β€” event-driven programs, game loops, and user interaction.
Intermediate Infinite While Q15: Menu-driven calculator
Scenario: Create an interactive calculator that keeps running until the user chooses to exit.
πŸ’‘ Solution:
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")
πŸ“– Explanation:

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.

Intermediate Infinite While Q16: ATM simulation
Scenario: Create an ATM system that allows deposit, withdraw, balance check, and exit.
πŸ’‘ Solution:
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
πŸ“– Explanation:

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.

Advanced Infinite While Q17: Guessing game with retry limit
Scenario: Create a number guessing game with infinite retries until the user guesses correctly.
πŸ’‘ Solution:
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!")
πŸ“– Explanation:

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.

Advanced Infinite While Q18: Interactive data entry system
Scenario: Create a system that keeps accepting user data until "done" is entered.
πŸ’‘ Solution:
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}")
πŸ“– Explanation:

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

🎯 Learning Goal: Apply while loops to solve practical, real-world problems.
Advanced Real-World Q19: Digital clock with alarm
Scenario: Create a digital clock that keeps running and triggers an alarm at a set time.
πŸ’‘ Solution:
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)
πŸ“– Explanation:

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.

Advanced Real-World Q20: Data validation with retry
Scenario: Keep asking for valid input until the user provides correct data format.
πŸ’‘ Solution:
while True:
    email = input("Enter email: ")
    if '@' in email and '.' in email:
        print("Valid email!")
        break
    print("Invalid email! Try again.")
πŸ“– Explanation:

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.

Advanced Real-World Q21: Student attendance tracker
Scenario: Mark attendance for students until all are marked or the teacher exits.
πŸ’‘ Solution:
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}")
πŸ“– Explanation:

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.

Advanced Real-World Q22: Shopping cart system
Scenario: Create a shopping cart that keeps accepting items until checkout.
πŸ’‘ Solution:
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}")
πŸ“– Explanation:

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.

Advanced Real-World Q23: Prime number generator up to N
Scenario: Generate all prime numbers up to a given number using while loops.
πŸ’‘ Solution:
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
πŸ“– Explanation:

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.

Advanced Real-World Q24: Text-based adventure game
Scenario: Create a simple text adventure game where the player makes choices until they win or lose.
πŸ’‘ Solution:
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!")
πŸ“– Explanation:

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

🎯 Learning Goal: Test your skills with challenging problems that require creative thinking.
Advanced Challenge Q25: Check if a number is palindrome
Scenario: Check if a given number is a palindrome (reads same forward and backward).
πŸ’‘ Solution:
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
πŸ“– Explanation:

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.

Advanced Challenge Q26: Binary to decimal converter
Scenario: Convert a binary number to decimal using while loop.
πŸ’‘ Solution:
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
πŸ“– Explanation:

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.

Advanced Challenge Q27: Greatest Common Divisor (GCD)
Scenario: Find the GCD of two numbers using the Euclidean algorithm with while loop.
πŸ’‘ Solution:
a, b = 48, 18
while b != 0:
    temp = b
    b = a % b
    a = temp
print(f"GCD: {a}")
# Output: GCD: 6
πŸ“– Explanation:

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.

Advanced Challenge Q28: Password strength checker
Scenario: Keep asking for a password until the user creates a strong password (min 8 chars, contains uppercase, lowercase, digit).
πŸ’‘ Solution:
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
πŸ“– Explanation:

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.

Loading Pyodide... 0%
Python Code Editor
========================================
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

πŸ“– Related Tutorials
  • For Loop vs While Loop
  • Break, Continue and Else in Loops
  • All Loops Assignments
πŸ“– Interview & FAQ Resources
  • Python Syntax & Variables Interview Questions
  • SQL - Displaying Data from Multiple Tables FAQ
  • Python Data Types Interview Questions
Previous: Nested While Loop Next: For Loop β†’