Python Loops – While – Class 11 & 12

UpComing SoftWare Training Demos

🚀 *Playwright With AI Testing Demo In Telugu*
🗓️ *Date:* 28 Oct2026, 08:00 PM IST
📝 *Register Now!:*
https://www.vlrt.in/3r
👥 *Join WA Community:*
https://www.vlrt.in/3w
💡 *Course Content:*
https://www.vlrt.in/3c
▶️ *Demo Videos:*
https://www.vlrt.in/3v

🚀 *Gen AI Engineer (Production Focused)*
🗓️ *Date:* 29th Oct 2026, 06:00PM IST
📝 *Register Now!:*
https://www.vlrt.in/gr
👥 *Join WA Community:*
https://www.vlrt.in/gw
💡*Course Content:*
https://www.vlrt.in/ai
▶️ *Demo Videos:*
https://www.vlrt.in/gv

🚀 *Vulnerability Management Training Demo*
🗓️ *Date:* 28th Oct 2026, 10:00 AM IST
📝*Register Now!:*
https://www.vlrt.in/vr
👥 *Join Community:*
https://www.vlrt.in/cw
💡 *Course Content:*
https://www.vlrt.in/vc
▶️ *Demo Videos:*
https://www.vlrt.in/Vm

While Loops in Python with Examples

A while loop in Python repeatedly executes a block of code as long as a specified condition remains true. It’s useful when you don’t know in advance how many times you’ll need to iterate.

Basic Syntax

python

while condition:
    # code to execute while condition is true
    # don't forget to modify the condition variable!

Example 1: Simple Counter

python

# Count from 1 to 5
count = 1
while count <= 5:
    print(f"Count: {count}")
    count += 1  # Increment count to eventually make the condition false

print("Loop ended!")

Output:

text

Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Loop ended!

Explanation:

  1. Initialize count to 1
  2. The loop runs as long as count <= 5 is true
  3. Inside the loop, we print the current count and increment it
  4. When count becomes 6, the condition becomes false and the loop ends

Infinite Loops, break, and continue in Python While Loops

1. Infinite Loops

An infinite loop occurs when a while loop’s condition never becomes False, causing it to run indefinitely.

Example of Infinite Loop:

python

while True:
    print("This will run forever!")

Common Causes:

  • Forgetting to update the variable in the condition
  • Incorrect loop condition
  • Intentional design (like server loops)

Practical Use Case (Controlled Infinite Loop):

python

while True:
    user_input = input("Enter 'quit' to exit: ")
    if user_input.lower() == 'quit':
        break
    print(f"You entered: {user_input}")

2. The break Statement

break immediately terminates the entire loop, skipping any remaining iterations.

Example:

python

count = 0
while count < 10:
    count += 1
    if count == 5:
        break
    print(count)
# Output: 1 2 3 4

Common Uses:

  • Early exit when a condition is met
  • User requests to quit
  • Error conditions

3. The continue Statement

continue skips the rest of the current iteration and moves to the next one.

Example:

python

count = 0
while count < 5:
    count += 1
    if count == 3:
        continue
    print(count)
# Output: 1 2 4 5

Common Uses:

  • Skipping specific values
  • Handling edge cases
  • Avoiding nested if statements

Comparison Table

ConceptEffectWhen to Use
Infinite LoopRuns indefinitelyServer loops, game loops
breakExits the loop completelyEarly termination conditions
continueSkips to next iterationSkip specific cases

Best Practices

  1. Avoid accidental infinite loops by ensuring your condition will eventually become False
  2. Use break sparingly – it can make code harder to follow
  3. Consider alternatives to continue like if-else statements when they improve readability
  4. Always have an escape route for intentional infinite loops (like a break condition)

Practical Example Combining All Three

python

while True:  # Infinite loop
    user_input = input("Enter a number (or 'done' to finish): ")
    
    if user_input.lower() == 'done':
        break  # Exit the loop
        
    if not user_input.isdigit():
        print("Invalid input!")
        continue  # Skip to next iteration
        
    number = int(user_input)
    if number % 2 == 0:
        print(f"{number} is even")
    else:
        print(f"{number} is odd")

This example shows:

  • An infinite loop (while True)
  • A break condition to exit
  • A continue to skip invalid inputs

The else Suite in Python’s while Loop

In Python, the while loop can have an optional else clause, which is executed when the loop condition becomes false. This is often called the “else suite” of the while loop.

Basic Syntax

python

while condition:
    # loop body
else:
    # else suite (executed when condition becomes false)

Key Points About the else Suite

  1. The else block executes only if the loop completes normally (i.e., the condition becomes false)
  2. It does not execute if the loop is terminated by a break statement
  3. It’s useful for situations where you want to execute some code when a loop finishes without finding what it was looking for

Simple Examples

Example 1: Basic while-else

python

count = 0
while count < 3:
    print(f"Count is {count}")
    count += 1
else:
    print("Loop completed normally")

Output:

text

Count is 0
Count is 1
Count is 2
Loop completed normally

Example 2: With break statement

python

count = 0
while count < 3:
    print(f"Count is {count}")
    if count == 1:
        break
    count += 1
else:
    print("Loop completed normally")

Output:

text

Count is 0
Count is 1

Notice the else block didn’t execute because we used break

Practical Example: Searching for an item

python

numbers = [1, 3, 5, 7, 9]
index = 0
while index < len(numbers):
    if numbers[index] == 4:
        print("Found 4!")
        break
    index += 1
else:
    print("4 not found in the list")

Output:

text

4 not found in the list

When to Use while-else

The else suite is particularly useful for search loops where you want to:

  1. Take some action if the item is found (using break)
  2. Take a different action if the item isn’t found (in the else clause)

This pattern is cleaner than using flags to track whether a search was successful.

Notebook

While Loops in Python with Examples

A while loop in Python repeatedly executes a block of code as long as a specified condition remains true. It’s useful when you don’t know in advance how many times you’ll need to iterate.

Basic Syntax python

while condition: # code to execute while condition is true # don’t forget to modify the condition variable!

msg = input("enter string to print n times")
n = int(input("How many time repeat"))
i = 0
while i<n:
    print(i+1,msg)
    i += 1
print("loop ended")
    
1 ram
2 ram
3 ram
4 ram
5 ram
6 ram
7 ram
8 ram
9 ram
10 ram
11 ram
12 ram
13 ram
14 ram
15 ram
16 ram
17 ram
18 ram
19 ram
20 ram
21 ram
22 ram
23 ram
24 ram
25 ram
26 ram
27 ram
28 ram
29 ram
30 ram
loop ended
Greet = "hi venkat"
# print(greet)
i = 0
while i<10:    
    i += 1
    print(i,Greet)

print("*******")
1 hi venkat
2 hi venkat
3 hi venkat
4 hi venkat
5 hi venkat
6 hi venkat
7 hi venkat
8 hi venkat
9 hi venkat
10 hi venkat
*******
# print 1 to N number
n = int(input("How many Number")) #10
i=1
while i<=n:    
    print(i)
    i += 1
1
2
3
4
5
6
# print 1 to N even number
# print 1 to N number
n = int(input("How many Number")) #100
i=2
while i<=n:
    print(i)
    i += 2
 
2
4
6
8
10
12
14
16
18
20
i = 100
while i>=1:
    print(i)
    i -= 1
    
100
99
98
97
96
95
94
93
92
91
90
89
88
87
86
85
84
83
82
81
80
79
78
77
76
75
74
73
72
71
70
69
68
67
66
65
64
63
62
61
60
59
58
57
56
55
54
53
52
51
50
49
48
47
46
45
44
43
42
41
40
39
38
37
36
35
34
33
32
31
30
29
28
27
26
25
24
23
22
21
20
19
18
17
16
15
14
13
12
11
10
9
8
7
6
5
4
3
2
1
# Count from 1 to 5
count = 1
while count <= 5:
    print(f"Count: {count}")
    count += 1  # Increment count to eventually make the condition false

print("Loop ended!")
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Loop ended!

Sum of First N Natural Numbers Using a While Loop in Python

#Sum of First N Natural Numbers

n = int(input("Enter a positive integer: "))
sum = 0
i = 1

while i <= n:
    sum += i
    i += 1

print(f"The sum of first {n} natural numbers is: {sum}")
The sum of first 10000 natural numbers is: 50005000

Sum of N Entered Numbers Using a While Loop in Python

n=int(input("enter n Vlue"))
sum=0
i=1
while i<=n:
    k = int(input(f"Enter number {i}: "))
    sum= sum + k
    i = i+1 
print (sum)
100
n = int(input("How many numbers do you want to sum? "))
sum_numbers = 0
count = 1  # Tracks how many numbers we've taken

while count <= n:
    num = float(input(f"Enter number {count}: "))
    sum_numbers += num
    count += 1
    

print(f"The sum of the {n} numbers is: {sum_numbers}")
The sum of the 5 numbers is: 15.0
 
n = int(input("How many numbers do you want to compare? "))
count = 0
max_num =  0 # Initialize to smallest possible number
min_num =  99999999999999999999999999999999999999999999999999999999 # Initialize to largest possible number

while count < n:
    num = float(input(f"Enter number {count + 1}: "))
    if num > max_num: 45 >33
        max_num = num # 45
    if num < min_num:  45 < 22
        min_num = num #22
    count += 1

print(f"Maximum number: {max_num}")
print(f"Minimum number: {min_num}")
Maximum number: 66.0
Minimum number: 22.0
# Print multiplication table for number 5
num = int (input("number"))
i = 1

print(f"Multiplication table of {num}:")
while i <= 10:
    print(f"{i} X {num} = {num * i}")
    i += 1

    #{num} x {i} =
Multiplication table of 88:
1 X 88 = 88
2 X 88 = 176
3 X 88 = 264
4 X 88 = 352
5 X 88 = 440
6 X 88 = 528
7 X 88 = 616
8 X 88 = 704
9 X 88 = 792
10 X 88 = 880

want to extract its last digit using a while loop in Python

# number = 45671
# last_digit = None

# while number > 0:
#     last_digit = number % 10 # Gets the last digit
#     number = number // 10     # Removes the last digit
   
#     # Break after first iteration since we only need the last digit
#     break  

# print("Last digit:", last_digit)  # Output: 5

a= 235//10 #23 5
a= a//10 #2 3
a= a//10 #
a
0

Count the Number of Digits and Sum of Digits in Python

number = -35695
count = 0
sum_digits = 0
temp = abs(number)  # Handle negative numbers
print(temp)
while temp > 0: #3
    last_digit = temp % 10 #3
    sum_digits += last_digit #28
    count += 1 #5
    temp = temp // 10 #0

print(f"Number of digits: {count}")
print(f"Sum of digits: {sum_digits}")
35695
Number of digits: 5
Sum of digits: 28
#789
#987


num = int(input("Enter a number: "))
original = num
reverse = 0

# Reverse the number
while num > 0:
    digit = num % 10 # 
    reverse = reverse * 10 + digit #7654
    num = num // 10 #4

print(f"Reversed number: {reverse}")

# Check if palindrome
if original == reverse:
    print(f"{original} is a palindrome!")
else:
    print(f"{original} is not a palindrome.")
Reversed number: 7654
4567 is not a palindrome.

Infinite Loops

while True:
    user_input = input("Enter 'quit' to exit: ")
    if user_input.lower() == 'quit':
        break
    print(f"You entered: {user_input}")
You entered: hi

The break Statement

break immediately terminates the entire loop, skipping any remaining iterations.

count = 0
while count < 10:
    count += 1          
    print(count)
    if count == 8:
        break
    
print("Python")

#  if count == 5:
     #     break
1
2
3
4
5
6
7
8
Python

The continue Statement

continue skips the rest of the current iteration and moves to the next one.

count = 0
while count < 4:
    count += 1
    if (count == 2 or count == 3):
        continue
    print(count)
# Output: 1 2 4 5
1
4
while True:  # Infinite loop
    user_input = input("Enter a number (or 'done' to finish): ") #DONE
    
    if user_input.lower() == 'done':
        break  # Exit the loop
        
    if not user_input.isdigit():
        print("Invalid input!")
        continue  # Skip to next iteration
        
    number = int(user_input)
    if number % 2 == 0:
        print(f"{number} is even")
    else:
        print(f"{number} is odd")
Invalid input!

The else Suite in Python’s while Loop

In Python, the while loop can have an optional else clause, which is executed when the loop condition becomes false. This is often called the “else suite” of the while loop.

# while condition:
#     # loop body
# else:
#     # else suite (executed when condition becomes false)
#Basic while-else
count = 0
while count < 3:
    print(f"Count is {count}")
    count += 1
else:
    print("Loop completed normally")
Count is 0
Count is 1
Count is 2
Loop completed normally

With break statement

count = 0
while count < 3:
    print(f"Count is {count}")
    if count == 1:
        break
    count += 1
else:
    print("Loop completed normally")
Count is 0
Count is 1
 

Similar Posts

  • Python Primitive Data Types & Functions: Explained with Examples

    1. Primitive Data Types Primitive data types are the most basic building blocks in Python. They represent simple, single values and are immutable (cannot be modified after creation). Key Primitive Data Types Type Description Example int Whole numbers (positive/negative) x = 10 float Decimal numbers y = 3.14 bool Boolean (True/False) is_valid = True str…

  • The print() Function

    The print() Function Syntax in Python 🖨️ The basic syntax of the print() function in Python is: Python Let’s break down each part: Simple Examples to Illustrate: 💡 Python Basic print() Function in Python with Examples 🖨️ The print() function is used to display output in Python. It can print text, numbers, variables, or any…

  • Keyword-Only Arguments in Python and mixed

    Keyword-Only Arguments in Python Keyword-only arguments are function parameters that must be passed using their keyword names. They cannot be passed as positional arguments. Syntax Use the * symbol in the function definition to indicate that all parameters after it are keyword-only: python def function_name(param1, param2, *, keyword_only1, keyword_only2): # function body Simple Examples Example 1: Basic Keyword-Only Arguments…

  • Raw Strings in Python

    Raw Strings in Python’s re Module Raw strings (prefixed with r) are highly recommended when working with regular expressions because they treat backslashes (\) as literal characters, preventing Python from interpreting them as escape sequences. path = ‘C:\Users\Documents’ pattern = r’C:\Users\Documents’ .4.1.1. Escape sequences Unless an ‘r’ or ‘R’ prefix is present, escape sequences in string and bytes literals are interpreted according…

  • Unlock the Power of Python: What is Python, History, Uses, & 7 Amazing Applications

    What is Python and History of python, different sectors python used Python is one of the most popular programming languages worldwide, known for its versatility and beginner-friendliness . From web development to data science and machine learning, Python has become an indispensable tool for developers and tech professionals across various industries . This blog post…

Leave a Reply

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