Search code examples
pythonsyntax-errorturtle-graphicspython-turtle

TypeError: Start must be an interger in python turtle drawing


so I'm trying to draw special-patterned square in python turtle, and I'm drawing odd line first due to the input of the user, if the type an odd number then it will be plus 1 and then divided by 2, else divided by 2, here's my code, and it shows this error when I'm trying to divide it

from turtle import *
color("blue"); speed(0)
from math import sqrt
edge = int(input())
line = int(input())
linenum = 3
def draw(edge,line):
    begin_fill(); rt(45); fd(sqrt(edge**2*2)/2); rt(90); fd(sqrt(edge**2*2)/2); rt(135); fd(edge); rt(90); end_fill()
    fd(edge); rt(180)
    begin_fill(); lt(45); fd(sqrt(edge**2*2)/2); lt(90); fd(sqrt(edge**2*2)/2); rt(135); end_fill(); fd(edge)
    
def base_square():
    global linenum
    draw(edge,line)
    pu(); fd(edge); lt(90); fd(edge); lt(90); pd()
    if line % 2 != 0:
        for i in range((line+1)/2):  
            for _ in range(linenum):
                draw(edge,line)
                rt(135); fd(sqrt(edge**2*2)); rt(45)
            pu(); bk(edge*(linenum+1)); rt(90); fd(edge*2); lt(90); pd()
            linenum += 2
    else:
        for i in range(line/2):  
            for _ in range(linenum):
                draw(edge,line)
                rt(135); fd(sqrt(edge**2*2)); rt(45)
            pu(); bk(edge*(linenum+1)); rt(90); fd(edge*2); lt(90); pd()
            linenum += 2


            
base_square()

Solution

  • Try using the following:

    for i in range((line+1)//2):  
    ...
    for i in range(line//2):
    

    The // operator returns the integer quotient instead of a float type. range only accepts int type input.

    Alternatively, because you're just running the same loop for both even and odd cases and only changing the number, all you have to do is

    for i in range((line+1)//2):
    

    for both cases. This will give the same result whether or not it is even or odd. (e.g. 4//2 = 2,(4+1)//2 = 2;(5+1)//2 works as expected)