Home > Back-end >  How to print only once in loop?
How to print only once in loop?

Time:04-17

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

CodePudding user response:

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

CodePudding user response:

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')
  • Related