turtle graphics - How to nest a function inside a function in Python -
i have test code working on learning python , wondering how nest function inside function in python (if possible). here code working with.
import turtle my_turtle = turtle.turtle() def square(length, angle): my_turtle.forward(length) my_turtle.left(angle) my_turtle.forward(length) my_turtle.left(angle) my_turtle.forward(length) my_turtle.left(angle) my_turtle.forward(length) def repeat(length, angle): square(length, angle) my_turtle.left(angle) square(length, angle) repeat(50, 45)
first - indentation wrong.
second - in square, not choose angle (it's kind of done deal).
third - for
loops thing:
def square(length): in range(4): my_turtle.forward(length) my_turtle.left(90)
then can use function like
def three_squares(): in range(20, 80, 20): # gives [20, 40, 60] square(i) my_turtle.left(10)
python lets pass functions functions, like
def multi(times, inter_angle, action, *args): # let choose **what action** repeat _ in range(times): action(*args) my_turtle.left(inter_angle) multi(2, 45, square, 50) # draws 2 squares offset @ 45 degrees
while can define function inside function, demonstrated @cdlane, less common thing do; if (a) binding values outer function inner 1 or (b) if want make sure no other functions can call inner one.
wiki
Comments
Post a Comment