Home > Enterprise >  For loop with desired output in Python
For loop with desired output in Python

Time:05-27

I am trying to write a for-loop. The desired output is attached.

import numpy as np
for i in np.arange(0,5,1):
    sigma(0)=10
    sigma(i 1)=sigma(i) 1
    print(sigma)

The desired output is

sigma=np.array([10,11,12,13,14])

CodePudding user response:

You can try the solutions below, although the question does not point the problem to be solved.

  1. Simplier step:
import numpy as np
sigma = np.arange(10,15,1)
print (f"sigma = np.arange({sigma})")
  1. In the codeblock below, the stop attribute can take any value assigned, since we are going to limit the output using the if statement.
import numpy as np 
for i in np.arange(start=0, stop=5, step=1):
    i = i   10
    if i < 15:
        print(i)
    else:
        break #dosomething 
  1. Type 3:
import numpy as np
for i in np.arrage(start=10, stop=15, step=1):
    print(i)

CodePudding user response:

Here's the correct loop:

In [78]: sigma = [10]
    ...: for i in range(4):
    ...:     sigma.append(sigma[-1] 1)
    ...: sigma
Out[78]: [10, 11, 12, 13, 14]

But if you want to set values in an array:

In [79]: sigma = np.zeros(5,int)   # initialize
    ...: sigma[0] = 10
    ...: for i in range(0,4):
    ...:     sigma[i 1] = sigma[i] 1
    ...:     

In [80]: sigma
Out[80]: array([10, 11, 12, 13, 14])

In both of these I initialize sigma to something - a list or array. I also display/print is AFTER the loop, not at each step. And I use [] for indexing, not ().

But if you are using numpy there's no need to iterate

In [81]: np.arange(10,15)
Out[81]: array([10, 11, 12, 13, 14])

In [82]: np.arange(5) 10
Out[82]: array([10, 11, 12, 13, 14])
  • Related