Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
165 views
in Technique[技术] by (71.8m points)

Repeating a function a set amount of times in python

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.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First let me double check if I understood what you need: you have to place numTries sequential calls to tryConfiguration(floorplan,numLights), and each call is the same as the others.

If it is so, and if tryConfiguration is synchronous, you can just use a for loop:

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

Please let me know if I'm missing something: there could be other solutions, like leveraging closures and/or recursion, if your requirements are different.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...