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

5th Nov 2020, 12:50 PM
Aditya
Aditya - avatar
7 Antworten
+ 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.
5th Nov 2020, 3:22 PM
Lothar
Lothar - avatar
+ 4
You want to check the prize not the index. So write items[n] instead of n
5th Nov 2020, 1:00 PM
Benjamin Jürgens
Benjamin Jürgens - avatar
+ 2
I added: `if num % 2 != 0: continue`
18th Feb 2021, 9:41 PM
David-Troi Sweatt
David-Troi Sweatt - avatar
+ 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)
18th Feb 2022, 6:44 PM
Rares
+ 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)
18th Aug 2021, 11:32 PM
Noah
Noah - avatar
5th Nov 2020, 4:57 PM
Mohsen Abbaspour
Mohsen Abbaspour - avatar
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)
6th Feb 2022, 10:27 AM
Jake Ambrose
Jake Ambrose - avatar