Updating a quantity after every iteration in a for-loop in Python

Question:

I am writing a for loop. I want to update sigma=10 with sigma calculated in the next line for every t. I present the current and expected output.

For t=0, sigma=10, sigma=0.5*10*(0-2)=-10.

For t=1, instead of sigma=10, I want to have sigma=-10 as calculated for t=0. Then sigma=0.5*-10*(1-2)=5

for t in range(0,2):
    sigma=10
    sigma=0.5*sigma*(t-2)
    print(sigma)

The current output is

-10
-5

The expected output is

-10
5
Asked By: user19862793

||

Answers:

sigma initial must be out of the loop, here is the correct code:

import numpy as np

sigma=10 
for t in range(0,2):
    sigma=0.5*sigma*(t-2)
    print(sigma)
Answered By: scli
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.