Count Even Numbers Between 1 to 100 Using While Loop in Python

Now we are going to discuss how you can count the number of even numbers between 1 and 100 using a while loop in Python:

Simple code:

num = 1
count = 0
while num <= 100:
    if num % 2 == 0:
        count += 1
    num += 1
print(count)

Output:

50

Code with comments:

# initialize the starting number and count to 0
num = 1
count = 0

# continue looping until the number reaches 100
while num <= 100:
    # check if the current number is even
    if num % 2 == 0:
        # increment the count by 1
        count += 1
    # increment the number by 1
    num += 1

# print the final count of even numbers
print(count)

Output:

50

In the above code, we initialize the starting number and count to 0.

We then use a while loop to continue checking each number from 1 to 100 for evenness.

If the current number is even, we increment the count variable by 1.

Finally, we print the count value, which is the total number of even numbers between 1 and 100.


Discover more from Python Mania

Subscribe to get the latest posts sent to your email.

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

Related Articles:

Recent Articles:

0
Would love your thoughts, please comment.x
()
x

Discover more from Python Mania

Subscribe now to keep reading and get access to the full archive.

Continue reading