Python Loops – While – Class 11 & 12

While Loops in Python with Examples

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)
  • break condition to exit
  • 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

Leave a Reply

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