Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Storing the previous value and reusing it in a loop

I am implementing a code that after debugging for a month I found out the problem that could be translated in the present simpler case:

for i in range(1,5):
    x=2
    if i==1:
        y=2*x
    else:
        y=2*ypred
    
    ypred=y
    print(i)
    print(ypred)
    
    print(y)

I want to store only the previous value to be reuse in the loop. However, after analysing the print results, I found out that ypred is not the previous value of y in each interaction but exactly the same.

1
4
4
2
8
8
3
16
16
4
32
32

I know this problem may be simple, but I am learning how to code for mathematical purposes.
How do I store only the previous value to be reused in the following interaction?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks in advance.

>Solution :

Moving prints in right places leads to this output:

x = 2
ypred = 0
for i in range(1, 5):
    print(f"{i=}")
    print(f"{ypred=}")
    if i == 1:
        y = 2 * x
    else:
        y = 2 * ypred
    print(f"{y=}")
    ypred = y
    print(f"===")

Output:

i=1
ypred=0
y=4
===
i=2
ypred=4
y=8
===
i=3
ypred=8
y=16
===
i=4
ypred=16
y=32
===

Is it desired output?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading