Search code examples
pythonpython-turtle

How do I put functions in a list in Python?


I would like to use a switch statement in Python, but since there is not a switch statement in python, I would like to use a list of functions. However, when I define the list, the functions are executed.

Here is my code:

shapes = [drawSquare(), drawRectangle(), myTurtle.circle(10), drawTriangle(), drawStar()]

Here is the output using turtle:

output

How do I define the list of functions without python running the functions?


Solution

  • Remove the brackets ()

    Ex:

    shapes = [drawSquare, drawRectangle, myTurtle.circle, drawTriangle, drawStar]
    

    Demo:

    def add(a,b):
        return a + b
    
    def sub(a,b):
        return a - b
    
    lst = [add, sub]
    for i in lst:
        print(i(3,2))