'How to print only once in loop?

b = input().split(' ')
c = list(map(int,b))
y = 0
for i in range(len(b)):
    if c[i] %2 == 0:
        print(c[i])
        y = 1
    elif i == len(c) - 1 & y == 0:
        print('No number that is divisible by 2')

Code takes a list of numbers as input, then it prints all values divisible by 2, but if there are no such values it should print about this only once. My code works properly only in certain cases. I know another implementation but i need solution within 1 loop



Solution 1:[1]

Add break:

b = input().split(' ')
c = list(map(int,b))
y = 0
for i in range(len(b)):
    if c[i] %2 == 0:
        print(c[i])
        y = 1
    elif i == len(c) - 1 & y == 0:
        print('No number that is divisible by 2')
        break

Solution 2:[2]

You may want to simplify by calculating the numbers divisible by 2 first, then deciding what to print:

nums = map(int, input().split(' '))
div2 = [i for i in nums if not i % 2]
if div2:
    for i in div2:
        print(i)
else:
    print('No number that is divisible by 2')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Andrey
Solution 2 Pi Marillion