For loop gets error saying (odd number - odd number) / 2 is a float

Viewed 38

I'm trying to make a function that makes a pyramid out of an odd number of asterisks (e.g. 1, 3, 5)

import math
baseInput = 0
while baseInput % 2 == 0:
    baseInput = int(input('Enter base length: '))
def drawPyramid(base):
    #makes variable for amount of asterisks that have to be drawn
    starcounter = 1
    for i in range(starcounter, base):
        #calculates number of spaces needed and prints them
        for i in range((base - starcounter + 1) // 2):
            print(' ', end='')
        #prints current amount of asterisks
        for i in range(starcounter):
            print('*', end='')
        print('\n')
        #increases amount of stars
        starcounter += 2
drawPyramid(baseInput - 1)

I thought the output of this would be:

  *
 ***
*****

Instead, I get an error saying

enter image description here

I don't understand why 5 - 1 gets considered a float.

4 Answers

Just use // (integer division) instead of / (float division), because range expects integers:

for i in range((base - starcounter) // 2):

range can not take floats. Try it like this.

def drawPyramid(base):
    #makes variable for amount of asterisks that have to be drawn
    starcounter = 1
    for i in range(starcounter, base):
        #calculates number of spaces needed and prints them
        for i in range((base - starcounter + 1) // 2):
            print(' ', end='')
        #prints current amount of asterisks
        for i in range(starcounter):
            print('*', end='')
        print('\n')
        #increases amount of stars
        starcounter += 2
drawPyramid(4)
  *

 ***

*****

Use integer division (//) instead of float division (/):

for i in range((base - starcounter) // 2)
Related