Print even numbers in a list

Asked

Viewed 89 times

2

I’m trying to get the code to print only as many even numbers as it finds and not list all the numbers it found. What I’m trying to make it appear on the screen:

5 números pares

What is appearing on the screen:

2

4

6

8

10

I’m using this code to solve the problem:

for i in range(10):

    if(i%2==0):

        print(i, "Números pares!")

I tested some codes but either errors happen or the result is the same.

1 answer

4


He prints the numbers because that’s what you had him do (put the print inside the loop - the detail is that your code actually prints the numbers 0, 2, 4, 6 and 8).

If you want the amount, then create a counter, update it within the loop and only print at the end:

qtd = 0
for i in range(10):
    if i % 2 == 0:
        qtd += 1

print(qtd, "números pares!")

You can also use the syntax of comprehensilist on, much more succinct and pythonic:

qtd = len([i for i in range(10) if i % 2 == 0])

If you are using Python >= 3.6 it is possible to use f-strings to print:

print(f"{qtd} números pares!")

Although, to have only the even numbers, just do the range jump 2 by 2:

print(len(range(0, 10, 2)), "números pares!")

Other option, for the specific case only consider the even numbers between zero and N (where N is not included), simply divide N by 2 and round up:

from math import ceil

# quantidade de números pares entre 0 e n (sendo n não-incluso)
def qtd_pares(n):
    return ceil(n / 2)

print(qtd_pares(10)) # 5 (pois o 10 não é incluso)
print(qtd_pares(11)) # 6 (pois o 10 agora é incluso)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.