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
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.
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.
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.
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.
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
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With