How to print even numbers in Python?

by beatrice.lesch , in category: Python , 2 years ago

How to print even numbers in Python?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by evans , 2 years ago

@beatrice.lesch  You can do it like this:

1
2
3
4
numbers=(1,2,45,20,3,12,35,19)
for i in numbers:
    if i%2==0:
        print(i,' Is Even')


Member

by jenifer , a year ago

@beatrice.lesch 

To print even numbers in Python, you can use a loop to iterate through a range of numbers and print only the even ones. Here's an example:

1
2
3
for i in range(1, 11):
    if i % 2 == 0:
        print(i)


In this code, the range(1, 11) function generates a sequence of numbers from 1 to 10. The loop then iterates through each number in this sequence, and the if statement checks if the number is even by using the modulo operator % to check if there is a remainder when the number is divided by 2. If there is no remainder (i.e. the number is even), the print() function is called to output the number to the console.


The output of this code will be:

1
2
3
4
5
2
4
6
8
10


Alternatively, you can use a while loop to achieve the same result:

1
2
3
4
5
i = 1
while i <= 10:
    if i % 2 == 0:
        print(i)
    i += 1


In this code, the loop continues to iterate until the variable i reaches the value of 10. The rest of the code is the same as the previous example.