7th Aug 2021, 7:16 AM
Mas'ud Saleh
Mas'ud Saleh - avatar
4 Antworten
+ 8
Because you declared the continue before n+=1 so when a odd number comes it becomes an infinite loop as the value of n never increases.So if you declare n+=1 before continue, it will work fine. Btw, no need to write the else statement. You could just write the n+=1 after the if statement instead of declaring inside if and it would work the same as you expected: https://code.sololearn.com/cqzrOK9RdDaB/#py Also using for loop is a much better option as @Lothar mentioned. You can make your code even shorter by using the built-in function sum and filter and using lambda.Like this: https://code.sololearn.com/c2DTGo0q4kZD/#py
7th Aug 2021, 7:47 AM
The future is now thanks to science
The future is now thanks to science - avatar
+ 7
Mas'ud Saleh , # you don't need an else clause (it contains only a 'continue' that is useless in this case and the increment) and there is also no need to increment 'n' at multiple places: [Edited]: # >>> please don't use names of python objects or classes like 'sum' as variable names ! items = [23, 555, 666, 123, 128, 4242, 990] sum_ = 0 n = 0 while n < len(items): num = items[n] if num%2==0: sum_ += num n += 1 print(sum_) # using a for loop is the better and more pythonic way of iterating: no need to calculare the length of the list, and no need to use a counter variable 'n': items = [23, 555, 666, 123, 128, 4242, 990] sum_ = 0 for num in items: if num % 2 == 0: sum_ += num print(sum_)
7th Aug 2021, 7:43 AM
Lothar
Lothar - avatar
+ 4
You put n += 1 after continue so it never runs when you get to a odd number it while just run forever
7th Aug 2021, 7:23 AM
Abs Sh
Abs Sh - avatar
0
continue before n += 1 may be causing an infinite loop…
7th Aug 2021, 5:16 PM
Jurandy
Jurandy - avatar