+ 1

What is wrong with the code? if you enter several commas in a row, the program does not delete one comma

l = (input('enter numbers separated by commas: ')) print(l) l_list = list(l) print(l_list) a = 0 for i in l_list: if i == ',': del l_list[a] a = a+1 else: a = a+1 print(l_list) def l_sum(x): s = 0 for i in x: s = s + int(i) return s print(l_sum(l_list))

6th Feb 2020, 9:41 AM
Dmitry Bezruchko
Dmitry Bezruchko - avatar
6 Respuestas
+ 3
You want to get only the entered numbers, not the commas? For this you normally just use: numbers = input().split(',')
6th Feb 2020, 9:52 AM
HonFu
HonFu - avatar
+ 4
It is the problem of deleting-while-iterating Look at this simple example Str = ',,' for i in range(2): del Str[i] # After first loop Str is ',' and the next loop trying to delete Str[1] will dump Your prog "accidently" works for some lists.
6th Feb 2020, 10:19 AM
Oma Falk
Oma Falk - avatar
+ 2
Ooh! "your list shrinks as well" I understood! Thanks a lot!
6th Feb 2020, 10:55 AM
Dmitry Bezruchko
Dmitry Bezruchko - avatar
+ 1
Oma has said it, but her post seems to be gone... If you delete an element, your list shrinks as well, so in that case you shouldn't increase your index variable. a = 0 for i in l_list: if i == ',': del l_list[a] else: a = a+1
6th Feb 2020, 10:18 AM
HonFu
HonFu - avatar
+ 1
There's another problem though: Your method (list(input())) will do this: 23,45 -> ['2', '3', ',', '4', '5'] I'm sure you don't want that?
6th Feb 2020, 10:20 AM
HonFu
HonFu - avatar
0
Yes And thanks for the tip! However, I do not understand why the cycle does not work here?
6th Feb 2020, 10:11 AM
Dmitry Bezruchko
Dmitry Bezruchko - avatar