Python Forum

Full Version: How to use += after breaking for loop?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

I am new to the forum and new to Python and maybe i did not post in the right part of the forum.

I have this code:
import numpy as np

mlist = [8,7,5,2,1,4,5,6,8]

i = min(mlist)
print("low", i)

t = mlist.index(i)

o = len(mlist)
print("elements", o)

p = slice(0,t+1)
print("slash", mlist[p])


print(mlist[-t-1::-1])

add = 1 + 2 + 3

for x in mlist[-t-1::-1]:
    if x >= add:
     break 
    x += x                         // it return 2, 4, 10 in the output but should return 1, 3, 8
    print("stop",x)    
Any explaination why i cant have the right output is appreciated.

Thank you
You've used x as your loop variable, so it is modified each time through the loop. If you want a variable to hold information across each cycle, you need to use a different variable.

On line 24 and 25 you modify and then print x. But when the loop runs again and goes back to line 21, your modifications are lost.

I'm guessing you're trying to do something like this:

total = 0
for x in mlist[-t-1::-1]:
    print(f"Checking {x} against {add}")
    if x >= add:
     break
    total += x
    print("stop",total)
First i did that but i initialized my variable inside de loop. I woke up this morning with the same idea.
Thanks for your reply and solution.

(Dec-30-2021, 09:28 PM)bowlofred Wrote: [ -> ]You've used x as your loop variable, so it is modified each time through the loop. If you want a variable to hold information across each cycle, you need to use a different variable.

On line 24 and 25 you modify and then print x. But when the loop runs again and goes back to line 21, your modifications are lost.

I'm guessing you're trying to do something like this:

total = 0
for x in mlist[-t-1::-1]:
    print(f"Checking {x} against {add}")
    if x >= add:
     break
    total += x
    print("stop",total)