Monday, August 25, 2025

๐ŸWHILE LOOP

While Loop in Python

Loops help us repeat code, but when we don’t know exactly how many times to repeat, the while loop is often the right choice.

For Loop vs While Loop

- A for loop is used when you know in advance how many times you want to run the loop (for example, printing numbers from 1 to 10). - A while loop is used when the number of iterations is not known in advance, and the loop should continue until a certain condition is True.

In short: - for → works well for counting or iterating through a sequence.
- while → works well for repeating until a condition changes.

Syntax of While Loop


while condition:
    # block of code to execute repeatedly

- condition → The loop keeps running as long as this condition is True. - If the condition becomes False, the loop stops. - Proper indentation is required for the loop body.

Basic Examples

1. Counting with while


i = 1
while i <= 5:
    print("Number:", i)
    i += 1

Output: prints numbers from 1 to 5.

2. Waiting for user input


password = ""
while password != "python123":
    password = input("Enter password: ")
print("Access granted!")

Common Mistakes

  • Forgetting to update the variable:
    
    i = 1
    while i <= 5:
        print(i)  # ❌ Infinite loop, because i is never updated
    
    ✅ Fix: Increment i inside the loop.
  • Using capitalized keyword: While instead of while → ❌ SyntaxError.
  • Wrong condition: Example: while 5: → Infinite loop, because 5 is always truthy. Always use a condition that can eventually turn False.
  • Indentation Errors: forgetting to indent after while statement.

More Use Cases

1. Countdown


count = 5
while count > 0:
    print(count)
    count -= 1
print("Blast off!")

2. Input validation


number = -1
while number < 0:
    number = int(input("Enter a positive number: "))
print("You entered:", number)

๐Ÿ’ก Practice Challenges

  1. Write a program to print numbers from 1 to 100 using a while loop.
  2. Create a simple password checker using while until the correct password is entered.
  3. Make a countdown timer from 10 to 1 that ends with "Happy New Year!".
  4. Keep asking the user for input until they type "exit".

What’s Next?

After the while loop, we will learn about break and continue statements, which give us more control inside loops.

➡️ Next: Break and Continue

⬅️ Back to Main Page

๐Ÿ–ฅ️ Practice in Browser

No comments:

Post a Comment

๐ŸWhat is scikitlearn??