+ 3
How do I solve this code coach problem?
This is the problem: A shop is running a promotion today! If an item's price is an odd number, you get that item for free! You use a list to store the prices of all items in the shopping cart. The given code uses a while loop to iterate over the list, calculates the price of all the items in the list, and output the result. Change the code to skip the odd prices, calculate the sum of only the even prices and outputs the result. This is the code: items = [23, 555, 666, 123, 128, 4242, 990] sum = 0 n = 0 while n < len(items): if n%2 != 0: #this the code written by me continue num = items[n] n += 1 sum += num print(sum)
7 Réponses
+ 11
Incredible , before 'continue' will be executed, you should increase the n counter, otherwise you run in an infinite loop. And please do not use names in a python program that are identical with internal names. 'sum' is a built-in function. You can use 'sum_' - that is ok.
+ 4
You want to check the prize not the index. So write items[n] instead of n
+ 2
I added:
`if num % 2 != 0:
continue`
+ 2
items = [23, 555, 666, 123, 128, 4242, 990]
sum = 0
n = 0
while n < len(items):
num = items[n]
if num % 2 != 0:
# n += 1 - but why is this neeeded? my code doesn't work without
continue
n += 1
sum += num
print(sum)
+ 1
#This worked for me
items = [23, 555, 666, 123, 128, 4242, 990]
total = 0
n = 0
while n < len(items):
num = items[n]
n += 1
if num % 2 != 0:
continue
total += num
print(total)
0
# https://www.sololearn.com/learning/1073/2281/4991/1
# Problem i had trouble with, tough odd item free code.
items = [23, 555, 666, 123, 128, 4242, 990]
sum = 0
n = 0
while n < len(items):
num = items[n]
n += 1
if(num % 2 != 0):
continue
sum += num
print(sum)