edesz
edesz

Reputation: 12406

Step through for Python loop with step size given in exponentials

I have a Python list

q_s = [1E2,1E4,1E8,0]

I am trying to loop through values from 1E2 to 1E8 in steps of 1E4. So, I need the loop values to be 1E2+0*1E4, 1E2+1*1E4, 1E2+2*1E4, etc.

Attempt with output:

Attempt:

Here is my attempt:

for j in range(q_s[0],q_s[2],q_s[1]):
    print(j)

Output:

Here is the error message that it gives me:

Traceback (most recent call last):
  File "C:\test.py", line 2, in <module>
    for q in range(q_s[0],q_s[2],q_s[1]):
TypeError: range() integer end argument expected, got float.
[Finished in 0.3s with exit code 1]

Additional information:

For the start, stop and step values, the start (1E2) and stop (1E4) values are realistic for what I am doing. The step value (1E4) is there just for testing purposes - in theory, I think that I should have freedom to use any value here - the code should not force me to pick certain step sizes for going through the for loop.

Question:

Is there a way to cycle through this loop using the start, stop and step sizes above?

Upvotes: 1

Views: 763

Answers (2)

Ahmad Wahbi
Ahmad Wahbi

Reputation: 23

You can also do

for i in [pow(2,j) for j in range(int(math.log(n,2)))] 

n being the limit number

Example:

import math
for i in [pow(2,j) for j in range(int(math.log(64,2))+1)]:
    print(i)

Output: 1 2 4 8 16 32 64

Upvotes: 0

ojii
ojii

Reputation: 4781

The problem is that xEy in Python returns a float, not an int. range only handles ints.

The solution is to cast your values to int, like this:

for j in range(int(q_s[0]), int(q_s[2]), int(q_s[1])):
    print j

Upvotes: 2

Related Questions