在python中重复一个函数一定次数

2024-06-01 23:10:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我在做一个介绍类,他们要求我重复一个函数一定的次数,因为我说这是一个介绍,所以大部分的代码是写的,所以假设函数已经定义好了。我必须重复tryConfiguration(floorplan,numLights)的时间量numTries请求。任何帮助都会很棒的:谢谢。

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.

Tags: theto函数invaluelevelwillpicture
3条回答

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

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

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

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

在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

相关问题 更多 >