Already looked at Google and past questions in here and couldn't find a simple and well-explained answer.
How to loop through a large number in python?
e.g. I would like to check how long it will take to loop between 1 and 1.2e+34 and print the final result.
Not sure how to write for look/while loop for this and I have no idea how to write 1.2e+34 in python language (For i = 1 to i = ?).
Python understands 1.2e34
, as a float, but you can cast it to an int. int(1.2e34)
.
If you want to loop between 1 and n
inclusive, you would normally use range(1, n+1)
.
Thus, in Python 3:
for i in range(1, int(1.2e34)+1):
print(i) # or do whatever you want
--
As FHTMitchell pointed out, in Python 2, the value is too large for range
or xrange
. You could use a while
loop instead.
i = 1
while i <= 1.2e34:
print i # or do whatever you want
i += 1