Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable step in a for loop

I am trying to loop between 0.01 and 10, but between 0.01 and 0.1 use 0.01 as the step, then between 0.1 and 1.0 use 0.1 as step, and between 1.0 and 10.0 use 1.0 as step.

I have the while loop code written, but want to make it more pythonic.

i = 0.01
while i < 10:
   # do something
   print i
   if i < 0.1:
       i += 0.01
   elif i < 1.0:
       i += 0.1
   else:
       i += 1

This will produce

0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1, 2, 3, 4, 5, 6, 7, 8, 9
like image 386
volc_nerd Avatar asked Jun 15 '16 21:06

volc_nerd


People also ask

What is the variable in a for loop?

In computer programming, a loop variable is a variable that is set in order to execute some iterations of a "for" loop or other live structure. A loop variable is a classical fixture in programming that helps computers to handle repeated instructions.

Can you create a variable in a for loop?

Often the variable that controls a for loop is needed only for the purposes of the loop and is not used elsewhere. When this is the case, it is possible to declare the variable inside the initialization portion of the for.

Do you need a variable for a for loop?

For Loop iterates each element from the list until the given range. So no need of any variable to check condition. While Loop iterates until the given condition is true.

Can you increment i in a for loop?

A for loop doesn't increment anything. Your code used in the for statement does. It's entirely up to you how/if/where/when you want to modify i or any other variable for that matter.


2 Answers

A special-purse generator function might be the right way to go. This would effectively separate the boring part (getting the list of numbers right) from the interesting part (the # do something in your example).

def my_range():
    for j in .01, .1, 1.:
        for i in range(1, 10, 1):
            yield i * j

for x in my_range():
    print x
like image 102
Robᵩ Avatar answered Oct 18 '22 05:10

Robᵩ


One approach would be to use two loops: one for the order of magnitude, and one for the values from 1 to 9:

for exp in range(-2, 1):
    for i in range(1, 10):
        print("{:.2f}".format(i * 10 ** exp))
like image 3
Robin Krahl Avatar answered Oct 18 '22 05:10

Robin Krahl