Python while Loops

🐍 Python while Loops — Full Tutorial

The while loop in Python is used to repeatedly execute a block of code as long as a condition is True.


🔹 1. Basic While Loop

count = 1

while count <= 5:
print("Count:", count)
count += 1

✅ Output:

Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
  • count += 1 is required to increment the counter. Otherwise, the loop runs forever (infinite loop).


🔹 2. Infinite While Loop

while True:
print("This will run forever")
break # Stop the loop
  • Use break to exit the loop.


🔹 3. Using break Statement

break immediately stops the loop:

i = 1

while i <= 10:
if i == 5:
break
print(i)
i += 1

✅ Output:

1
2
3
4

🔹 4. Using continue Statement

continue skips the current iteration and moves to the next:

i = 0

while i < 5:
i += 1
if i == 3:
continue
print(i)

✅ Output:

1
2
4
5

🔹 5. Using else with While

Python allows else after while, executed if the loop ends normally (not by break):

i = 1

while i <= 5:
print(i)
i += 1
else:
print("Loop finished successfully!")

✅ Output:

1
2
3
4
5
Loop finished successfully!

🔹 6. Practical Examples

6.1 Sum of Numbers Until User Enters 0

total = 0

while True:
num = int(input("Enter a number (0 to stop): "))
if num == 0:
break
total += num

print("Total:", total)


6.2 Password Validation

password = "vipul123"

while True:
user_input = input("Enter password: ")
if user_input == password:
print("Access granted!")
break
else:
print("Incorrect password, try again.")


6.3 Multiplication Table

num = int(input("Enter a number: "))
i = 1

while i <= 10:
print(f"{num} x {i} = {num*i}")
i += 1


🔹 7. Infinite Loop Warning

  • Avoid infinite loops without a condition change or break statement:

while True:
print("Oops! Infinite loop…")

🔹 8. Tips & Best Practices

  1. Always ensure the loop condition will eventually be False.

  2. Use break and continue wisely for control flow.

  3. Use else after while for clean code when needed.


🧠 Practice Exercises

  1. Print numbers from 10 to 1 in descending order using while.

  2. Take input repeatedly until the user enters a negative number.

  3. Find the factorial of a number using while loop.

  4. Sum all even numbers from 1 to 50 using while.

  5. Print all digits of a number entered by the user individually.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *