Given a sequence of non-negative integers, where each number is written in a separate line. The sequence ends with 0. Print the number of even elements of the sequence.
**DON'T use ****if **statement.
so this is my approach
a = -1
while a!=0:
a = int(input())
for i in range(a):
if a == 2*i 1:
break
else:
print(a)
more potential approach but it seems to be wrong
while True:
a = int(input())
for i in range(1, a 1):
if a == 2*i 1:
break
else:
print(a)
CodePudding user response:
n_type = ("Even", "Odd")
arr = [0, 1, 2, 3, 4, 5, 6]
for num in arr:
print(n_type[num%2])
You can also do this without the loop if you want to take input from the user.
CodePudding user response:
This should solved your problem.
Note: False converted to int is 0 and True converted to int is 1
#sequence
seq = [3, 4, 6, 8, 9, 0]
#count
cnt_even = 0
#loop through the seq
for n in seq:
#if it's false add 0 if it's true add 1
cnt_even = (n % 2 == 0)
#print count
print(cnt_even)
Output
4
CodePudding user response:
Just use sum
. Using modulus we can get 0
for even and 1
for odd. Then we simply invert (^
) it, turning our 0
's to 1
's and vice-versa.
seq = (12, 15, 34, 76, 21)
cnt = sum(i%2^1 for i in seq) #3
If the while
loop is a necessary way to get each integer, then just use it to gather all the integers, and sum
what you gathered (as above) after you gathered all of it.
CodePudding user response:
Just use While loop instead of 'if', put the condition inside and then put a 'break;' at the end inside the while for not executing the loop twice. if you want to take inputs from the user just make a nested loop, one for the value inputs and another for checking..