# Two ways to solve the problem in "19.Create your own"

#1

I want to repalce items in a if it can't be divided by 5.
If I code in the former way,it works.
But the latter one seems uncorrect.Obviously,a doesn't change.
What't wrong with the second one?

``````a=range(2,120,3)
for i in range(len(a)):
if a[i]%5==0:
print a[i]
else:
a[i]=0
print a``````

It returns:

``````5
20
35
50
65
80
95
110
[0, 5, 0, 0, 0, 0, 20, 0, 0, 0, 0, 35, 0, 0, 0, 0, 50, 0, 0, 0, 0, 65, 0, 0, 0, 0, 80, 0, 0, 0, 0, 95, 0, 0, 0, 0, 110, 0, 0, 0]
None``````

``````a=range(2,120,3)
for i in a:
if i%5==0:
print i
else:
i=0
print a``````

It returns:

``````5
20
35
50
65
80
95
110
[2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35, 38, 41, 44, 47, 50, 53, 56, 59, 62, 65, 68, 71, 74, 77, 80, 83, 86, 89, 92, 95, 98, 101, 104, 107, 110, 113, 116, 119]
None``````

#2

@malvinawang,
Using

``````a=range(2,36,3)
run_count=0
for i in a:
run_count=run_count+1
print("Before IF {0}<<--{1}".format(i,run_count)),
if i%5==0:
print("=After IF  ="),
else:
i=0
print("=After ELSE="),
print(" {0}<<--{1}".format(i,run_count))

print a``````

having the [output]

``````Before IF 2<<--1 =After ELSE=  0<<--1
Before IF 5<<--2 =After IF  =  5<<--2
Before IF 8<<--3 =After ELSE=  0<<--3
Before IF 11<<--4 =After ELSE=  0<<--4
Before IF 14<<--5 =After ELSE=  0<<--5
Before IF 17<<--6 =After ELSE=  0<<--6
Before IF 20<<--7 =After IF  =  20<<--7
Before IF 23<<--8 =After ELSE=  0<<--8
Before IF 26<<--9 =After ELSE=  0<<--9
Before IF 29<<--10 =After ELSE=  0<<--10
Before IF 32<<--11 =After ELSE=  0<<--11
Before IF 35<<--12 =After IF  =  35<<--12
[2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35]``````

one can conclude
that you have NO influence on the =local= variable `i` of the FOR-IN loop !!!

#3

Get it.
It's so kind of you,thank a lot!

#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.