1

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?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
daniel
  • 1,446
  • 3
  • 29
  • 65
  • 4
    remove the brackets `()` – Rakesh Sep 21 '20 at 12:13
  • 4
    Does this answer your question? [Store functions in list and call them later](https://stackoverflow.com/questions/27472704/store-functions-in-list-and-call-them-later) and [Python argument binders](https://stackoverflow.com/questions/277922/python-argument-binders) – Karl Knechtel Jul 01 '22 at 01:41

3 Answers3

6

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))
Rakesh
  • 81,458
  • 17
  • 76
  • 113
1

By adding the () after the function name you are calling the function. To have a list of the callable functions simply change your example to read:

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

and to call one of the shapes do shapes[pos](args) e.g. to draw the circle per your example: shapes[2](10) (for those who aren't aware list positions begin at 0).

Elephant
  • 446
  • 1
  • 7
  • 19
1

You need to pass the reference to the function (drawSquare) in the list, not the function (drawSquare()) because you don't want your function called exactly at the moment when it is declared.

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

You can later call the functions using

[i(10) for i in shapes]

Or you can use a for loop if you want to give different arguments to each function.

  • Using `f` in your list comprehension rather than `i` as they're functions seems like a better idea. Also, list comprehensions are awesome, _but_ if you don't actually need a list of the results, a regular old for loop is a better idea. – Chris Jul 02 '22 at 17:59