python重复执行_在python中重复执行功能一定次数

1586010002-jmsa.png

I am doing an intro class and they are asking me to repeat a function a certain amount of times, as I said this is an intro so most of the code is written so assume the functions have been defined. I have to repeat the tryConfiguration(floorplan,numLights) the amount of time numTries requests. any help would be awesome :D thank you.

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.

解决方案

Loop in the range of numTries and call the function each time.

for i in range(numTries):

tryConfiguration(floorplan,numLights)

If using python2 use xrange to avoid creating the whole list in memory.

Basically you are doing:

In [1]: numTries = 5

In [2]: for i in range(numTries):

...: print("Calling function")

...:

Calling function

Calling function

Calling function

Calling function

Calling function