Home > Enterprise >  Updating a quantity after every iteration in a for-loop in Python
Updating a quantity after every iteration in a for-loop in Python

Time:08-30

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

CodePudding user response:

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)
  • Related