+ 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))
6 odpowiedzi
+ 3
You want to get only the entered numbers, not the commas?
For this you normally just use:
numbers = input().split(',')
+ 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.
+ 2
Ooh! "your list shrinks as well" I understood! Thanks a lot!
+ 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
+ 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?
0
Yes
And thanks for the tip!
However, I do not understand why the cycle does not work here?