Question

size = int(input("Enter an odd number width: "))
    for row in range(1, (size+1)/2, 1):
        for character in range(1, size):

            print("*"*character)

Why does it keep telling me "float object cannot be interpreted as an integer"? I know its because of the (size+1)/2 but I don't think it should make a difference?

Its supposed to create a triangle that looks like this:

*
***
*****
*******
*********
***********
*************

(rows are the width+1/2, and the entered number is the largest row of asterisks, also the rows increase by increments of 2 each time (i.e. 1, 3, 5, 7, 9, 13).

Was it helpful?

Solution

Because (size+1)/2 could theoretically have a fractional part, Python always returns a floating point number from it. range doesn't accept floats because there is no general way to turn it into an integer without potentially losing information. Neither of these steps special-cases the particular inputs that don't trigger these problems.

You don't care about those things, because you consider size being even to be an invalid input. But Python doesn't know you don't care about the potential data loss unless you tell it - which you can do like this:

(size + 1) // 2

This removes the fractional part of the number, and only gives you the integer part (ie, rounded toward minus infinity).

OTHER TIPS

because float object cannot be interpreted as integer. Use integer division:

(size + 1) // 2

Otherwise it will result on a float number (on Python 3)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top