在Python中重复调用函数指定次数

0 投票
3 回答
9685 浏览
提问于 2025-04-18 12:05

我正在上一个入门课程,他们让我把一个函数重复执行一定次数。因为这是入门课程,所以大部分代码已经写好了,可以假设这些函数已经定义好了。我需要把tryConfiguration(floorplan,numLights)这个函数重复执行numTries次。任何帮助都会很棒 :D 谢谢你。

def runProgram():
  #Allow the user to open a floorplan picture (Assume the user will select a valid PNG floodplan)
  myPlan = pickAFile()
  floorplan = makePicture(myPlan)
  show(floorplan)

  #Display the floorplan picture

  #In level 2, set the numLights value to 2
  #In level 3, obtain a value for numLights from the user (see spec).
  numLights= requestInteger("How many lights would you like to use?")

  #In level 2, set the numTries to 10
  #In level 3, obtain a value for numTries from the user.
  numTries= requestInteger("How many times would you like to try?")

  tryConfiguration(floorplan,numLights)

  #Call and repeat the tryConfiguration() function numTries times. You will need to give it (pass as arguments or parameterS)
  #   the floorplan picture that the user provided and the value of the numLights variable.

3 个回答

0

当我们需要多次执行同一段代码时,使用某种循环通常是个不错的主意。

在这种情况下,你可以使用“for循环”:

for unused in range(numtries):
    tryConfiguration(floorplan, numLights)

另一种更直观的方法(虽然有点笨重)是使用while循环:

counter = 0
while counter < numtries:
    tryConfiguration(floorplan, numLights)
    counter += 1
1

首先让我确认一下我是否理解你的需求:你需要连续调用 numTriestryConfiguration(floorplan,numLights),而每次调用都是一样的。

如果是这样,并且 tryConfiguration 是同步的,你可以直接使用一个 for 循环来实现:

for _ in xrange(numTries):
  tryConfiguration(floorplan,numLights)

如果我有什么遗漏,请告诉我:如果你的需求不同,可能还有其他解决方案,比如使用闭包和/或递归。

1

在numTries的范围内循环,每次都调用这个函数。

for i in range(numTries):
      tryConfiguration(floorplan,numLights)

如果你使用的是python2,建议用xrange,这样可以避免在内存中创建整个列表。

基本上你在做的事情是:

In [1]: numTries = 5

In [2]: for i in range(numTries):
   ...:           print("Calling function")
   ...:     
Calling function
Calling function
Calling function
Calling function
Calling function

撰写回答