0

I don't know if this is entirely recusion related but i added a small function within my main function to block non-integer inputs with

def main(depth, size):
    depth = eval(input("Enter depth that is an integer: "))
    if (isinstance( depth, int)) == False:
        print( 'Not an integer' )
        main(depth, size)
    else:
        pass
    turtle.left(120)
    turtle.speed(100)
    triangle(depth, size)

def triangle(depth, size):
    if depth == 0:
        pass
    else:
        turtle.forward(size)
        triangle(depth-1, size/2)
        turtle.right(120)
        turtle.forward(size)
        turtle.left(120)
        triangle(depth-1, size/2)
        turtle.right(120)
        turtle.right(120)
        turtle.forward(size)
        turtle.right(120)

main(depth, 100)

when I input an integer the program runs fine, when I input a non-int, it returns and tells me it's not an integer and returns to the input stage. then when i put in an integer, it starts drawing the picture as it should, then goes a little bit further, gets hung up at a recurson on line 27 with "triangle(depth-1, size/2)".

I'm so close to finishing this program, I just need to make it harder to crash.

4

1 回答 1

1

用户输入不是(非尾)递归的好候选,因为深度是无限的。只需迭代地执行它:

def main(size):
    while True:
        depth = input("Enter depth that is an integer: ")
        try:
            depth = int(depth)
        except ValueError:
            print('Not an integer')
        else:
            break

    turtle.left(120)
    turtle.speed(100)
    triangle(depth, size)
于 2013-09-14T23:27:09.730 回答