Home > Enterprise >  Maximum recursion depth exceeded in comparison in python turtle
Maximum recursion depth exceeded in comparison in python turtle

Time:10-30

I wrote this recursive code which draws a hexagon spiral in turtle and then is supposed to draw a square spiral. But instead it sends me an error "maximum recursion depth exceeded in comparison". Yet it works when I execute both functions in separate files. In both cases the functions take as a parameter the number of spirals n. Could someone explain to me why please.

def hexagon(n):
    if n>=1:
        forward(n)
        left(60)
    hexagon(n-1)
hexagon(100)
clearscreen()

def square(n):
    if n>=1:
        forward(n*5)
        right(90)
    square(n-1)
square(50) 

CodePudding user response:

This is due to an indentation error:

if n>=1:
    forward(n)
    left(60)
hexagon(n-1)

Which should be:

if n>=1:
    forward(n)
    left(60)
    hexagon(n-1)

And similarly in the square() function. The complete code:

from turtle import *

def hexagon(n):
    if n >= 1:
        forward(n)
        left(60)
        hexagon(n-1)

def square(n):
    if n >= 1:
        forward(n*5)
        right(90)
        square(n-1)

hexagon(100)
clearscreen()
square(50)

done()
  • Related