0
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

2
  • 2
    If you only want to print once, don't do it in the loop. Put it after the loop. Commented Apr 16, 2022 at 22:16
  • You could use the mod% function Commented Apr 16, 2022 at 22:18

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

thx, but problem was that i used '&' instead of 'and'
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.