TypeError: 'float' object cannot be interpreted as an integer in Python

Dung Do Tien Sep 05 2021 180

Hello you guys, I am a newbie in Python and I'm also studying more about Python.
I have a small assignment, I want to loop and print a range of numbers. Like this:

for i in range( 2.1, 5 ):
        print( i )

My code needs to be printed:

2.10000 2.20000 2.30000 ....

But I get an exception TypeError: 'float' object cannot be interpreted as an integer when I run the code above.

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    for i in range(3.3, 5 ):
TypeError: 'float' object cannot be interpreted as an integer

And I am using python 3.8.2

Anyone can explain it to me? How can I solve it?

Thanks for any response.

Have 1 answer(s) found.
  • N

    Nguyễn Hồng Quân Sep 05 2021

    The range() method only works with integers, not floats. But you can create your own range generator that will do what you want:

    def frange(start, stop, step=1):
        i = start
        while i < stop:
            yield i
            i += step 

    for i in frange(3.3, 5) will give you the output you want.

    Note, however, that frange unlike range, it will return a generator, not a list.

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close