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.