Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/365.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中多次重复函数_Python_Function_Loops_Jython_Repeat - Fatal编程技术网

在python中多次重复函数

在python中多次重复函数,python,function,loops,jython,repeat,Python,Function,Loops,Jython,Repeat,我正在做一个介绍类,他们要求我重复一个函数一定的次数,正如我说的,这是一个介绍,所以大部分代码都是编写的,所以假设函数已经定义。我必须重复tryConfigurationfloorplan,numLights会显示numTries请求的时间量。任何帮助都会很棒:D谢谢 def runProgram(): #Allow the user to open a floorplan picture (Assume the user will select a valid PNG floodplan)

我正在做一个介绍类,他们要求我重复一个函数一定的次数,正如我说的,这是一个介绍,所以大部分代码都是编写的,所以假设函数已经定义。我必须重复tryConfigurationfloorplan,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.

在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

当我们谈论多次重复某个代码块时,通常最好使用某种循环

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

for unused in range(numtries):
    tryConfiguration(floorplan, numLights)
使用while循环可能是一种更直观的方式,尽管更笨重:

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

首先,让我仔细检查一下我是否理解您的需要:您必须对tryConfigurationfloorplan、numLights进行numTries顺序调用,并且每个调用都与其他调用相同

如果是这样,并且tryConfiguration是同步的,则可以使用for循环:

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

如果我遗漏了什么,请告诉我:如果您的要求不同,可能会有其他解决方案,如利用闭包和/或递归。

我们很乐意帮助您解决StackOverflow上的这些问题,但请发布您迄今为止的尝试。对于大量numTries,请改用。不同之处在于,在开始循环之前,xrange不会在内存中创建一个非常大的列表。@JamieCockburn,我为xrange编辑过,xrange仅用于Python2通常在python中,我们还使用_u表示一个未使用的值:对于rangenumtries中的_u:。。。