-1

I'm trying to make a function that allows you to repeat a given action a set number of times. But no matter what number I put in the "repeat" argument, it only executes "action" once. Here's the code:

def repeat(repeat,action):
  for num in range(repeat):
    action


repeat(3,print("text"))

Here's a varient of the code that still failed:

def doUntil(condition, action):
  while condition != True:
    action
petezurich
  • 9,280
  • 9
  • 43
  • 57
Charlie
  • 1
  • 1
  • Welcome to Stack Overflow. In order to use the function like this, you first need to have something that *can be passed to the function and used later*. When you write `repeat(3,print("text"))`, this means: **call `print("text")` now** (which will display the text), and call `repeat` using **the return value from `print`** (which will be `None`). Please see the linked duplicates for a full explanation. – Karl Knechtel Apr 14 '23 at 16:11
  • Parameters are evaluated before calling the repeat function so your action only contains the result not the function call. For a single function, you could define your repeat function to accept a function and its parameters and make the actual calls inside your own loop: `def repeat(times,func,*args,**kwargs): for _ in range(times):func(*args,**kwargs)`. You would then call it with the repeat count, the function name and the parameters to give it: `repeat(3,print,"hello world")` – Alain T. Apr 14 '23 at 17:24

1 Answers1

3

The issue with your first code snippet is that you are calling the print() function when passing it as an argument to the repeat() function. This means that the print() function will be executed before the repeat() function is even called, and the return value of print() (which is None) will be passed as the action argument to repeat(). So essentially, you are just passing None to repeat() as the action argument, and then trying to execute it repeatedly. So you need to do it this way to create a new function and pass it as an argument like this.

def repeat(repeat, action):
  for num in range(repeat):
    action()

def print_text():
  print("text")

repeat(3, print_text)

Output:

text
text
text
A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103