3

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
  • 914
  • 2
  • 12
  • 31

2 Answers2

8

use numpy's arange instead of range:

import numpy as np
for x in np.arange(0, 1, 0.1):
    print(x)
sacuL
  • 42,057
  • 8
  • 58
  • 83
  • 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
3

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.

Simon
  • 8,992
  • 8
  • 49
  • 76