Rakibul Islam
Rakibul Islam

Reputation: 197

how can i use floating point number for increment in for loop by python

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

Upvotes: 5

Views: 11792

Answers (1)

Kartikeya Jha
Kartikeya Jha

Reputation: 91

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 

Upvotes: 9

Related Questions