7

I want to make a for loop that looks like this:

for x in range(0, 1, 0.1):
    print(x)

obviously it throws this error:

Traceback (most recent call last): File "", line 1, in for i in range(0, 1, 0.1): TypeError: 'float' object cannot be interpreted as an integer

So it there a way in python 3.6 to make a for loop with floating point?

Tissuebox
  • 1,016
  • 3
  • 14
  • 36

2 Answers2

12

use numpy's arange instead of range:

import numpy as np
for x in np.arange(0, 1, 0.1):
    print(x)
sacuL
  • 49,704
  • 8
  • 81
  • 106
  • 1
    Keep in mind you may not get exactly the numbers you expect, because `0.1` can't be represented exactly as a finite binary fraction. I like Simon's approach of using integers and dividing by 10 better; it's less prone to accumulated rounding errors. – kindall Mar 02 '18 at 01:26
7

Why not divide an integer and convert it into a float value?

for x in range(0, 10, 1):
    print(x/10)

Here you range from 0 to 10 and the divide the output by 10 to get a floating point.

Xantium
  • 11,201
  • 10
  • 62
  • 89
  • yes. I kinda should have thought about this, I guess its past experience from python2.x that made me scared to divide integer – Tissuebox Jul 30 '21 at 07:28