2

I want to use float number in for loop.So I wrote this code:

k=1
for i in range(0,3,0.2):
    for j in range(k,k+3,1):
        print("I= %i J=%i"%(i,j))
        k=k+0.2

But the following error occured:

Traceback (most recent call last):
  File "C:\Users\Md. Rakibul Islam\Desktop\URI practise.py", line 2, in <module>
   for i in range(0,3,0.2):
TypeError: 'float' object cannot be interpreted as an integer
Rakibul Islam
  • 167
  • 1
  • 2
  • 14
  • `range` only works with integers. If you want to use use floating point values in your `for` loop, you'll have to write your own generator than works like `range`. But note that this is not a good idea, as floating point values are imprecise and will accumulate error as you go. – Jonathon Reinhart Jun 25 '18 at 13:15
  • 6
    Possible duplicate of [How to use a decimal range() step value?](https://stackoverflow.com/questions/477486/how-to-use-a-decimal-range-step-value) –  Jun 25 '18 at 13:26

1 Answers1

7

Python has its limitations when it comes to for loop increments. Import numpy and use arange numpy.arange(start, stop, increment) start meaning the starting point of the loop, stop meaning the end point of the loop, and increment is the floating point increment. Here is your code:

import numpy
k=1
for i in numpy.arange(0,3,0.2):
    for j in numpy.arange(k,k+3,1):
         print("I= %i J=%i"%(i,j))
         k=k+0.2 
Kartikeya Jha
  • 71
  • 1
  • 2