Use a while loop with if statement condition i % 2 == 0 then only print the first 10 even numbers in Python.
Example print the first 10 even numbers using the while loop in Python
Simple example code prints even numbers of user input values using a while loop in Python. You can use list objects to store value, here we are printing the value using the end keyword.
x = int(input("Enter a number: "))
i = 1
while i <= x:
if i % 2 == 0:
print(i, end=" ")
i = i + 1
Output:
Without if statement
num = 2
while num <= 20:
print(num)
num = num + 2
Output:
2
4
6
8
10
12
14
16
18
20
Here’s a simple Python program that uses a while
loop to print the first 10 even numbers:
# Initialize a counter and the first even number
counter = 0
even_number = 2
# Use a while loop to print the first 10 even numbers
while counter < 10:
print(even_number, end=' ')
# Increment the counter and update the even number
counter += 1
even_number += 2
# Output:
# 2 4 6 8 10 12 14 16 18 20
In this program, the counter
variable keeps track of how many even numbers have been printed, and the even_number
variable holds the current even number. The loop continues until the counter reaches 10, printing each even number and updating the counter and even number in each iteration.
Do comment if you have any doubts or suggestions on this Python even number topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Explanation of this code
x = int(input(“Enter a number: “))
i = 1
while i <= x:
if i % 2 == 0:
print(i, end=" ")
i = i + 1
in the first line input is taken and the type of input is specified as int.
then in the second line a variable is declared with value 1
the third line declares a while loop with condition as it will run until the value of i will be less than or equal to x
fourth line checks a condition whether the remainder of i/2 is 0 or not, if it is 0 then it will be printed , if not not then it will not be printed
the the thing end=” ” means that each print value will be printed in the same line
the last line means i’s value will increment by 1 after one print is done
I hope this was helpful for you Rohini didi, i said didi as am in std 8th 🙂
THANK YOU!!!
wonderful
C = 0
i = 1
while C != 10:
if i % 2 == 0:
print (i)
C = C+1
i = i +1