'Python: Print only when the sum is not zero
If the sum of mult_list or non_mult_list is equal to zero, I don't want it print 0 out as below, it doesn't need to print anything. What should I add to restrict this situation?
Here is my code
n , m = map(int, input().split())
num_list = list(map(int,input().split()))
mult_list=[]
non_mult_list=[]
if m >= 2 and m <= 9:
for i in (num_list)[:n]:
if i%m == 0:
mult_list.append(i)
for j in (num_list)[:n]:
if j%m != 0:
non_mult_list.append(j)
print (sum(mult_list))
print (sum(non_mult_list))
Here is my input:
2 9
5 7
Then its output:
0
12
Solution 1:[1]
n , m = map(int, input().split())
num_list = list(map(int,input().split()))
mult_list=[]
non_mult_list=[]
if m >= 2 and m <= 9:
for i in (num_list)[:n]:
if i%m == 0:
mult_list.append(i)
for j in (num_list)[:n]:
if j%m != 0:
non_mult_list.append(j)
sum_mult_list = sum(mult_list)
sum_non_mult_list = sum(non_mult_list)
if sum_mult_list: # edited
print(sum_mult_list)
if sum_non_mult_list: #edited
print(sum_non_mult_list)
Solution 2:[2]
if sum(mult_list) != 0:
print(sum(mult_list))
if sum(non_mult_list) != 0:
print(sum(non_mult_list))
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 | Sharim Iqbal |
| Solution 2 | S P Sharan |
