[Tutor] Repeating a routine

Brian van den Broek broek at cc.umanitoba.ca
Wed Feb 22 15:58:24 CET 2006


John Connors said unto the world upon 22/02/06 05:43 AM:
> G'day,
> 
> With my only programming experience being C-64 Basic I'm finding that I 
> struggle a bit understanding some of the concepts of Python, I wish I 
> could block basic right out of my brain.
> 
> One of the things I can't get a grasp of is how to repeat a routine many 
> times. For example a simple dice game where 6 dice are rolled, any that 
> come up as 1 are kept, you keep rolling the dice until a 1 is not rolled.
> 
> A program to do that would need to generate a random number between 1 
> and 6 many times. In basic I would have made a sub routine for the 
> random number. Only way I can think of to do it in python is to have a 
> seperate script.
> 
> And at the end of the game I might want to play again and it would be 
> nice to have something like - Play dice game again (y/n). I'm not sure 
> how to run the program again other then re-loading it.
> 
> I know goto and gosub are evil, bad habits but I'm starting to miss them.
> 
> John


Hi John,

I came to python with only some ill-recalled BASIC, and I also 
(initially) missed goto, etc. You'll get over it :-)

See if the examples below give you a push. (I've purposely chosen ones 
silent on the die-rolling logic.)

 >>> def doit():
	print "Working!"

	
 >>> for i in range(6):
	doit()

	
Working!
Working!
Working!
Working!
Working!
Working!
 >>>

That is a minimal way to define some action and do it repeatedly. You 
will also need to return some value for your use case. So consider:

 >>> def getit():
	val = raw_input("Gimme!\n")
	return val

 >>> vals = []
 >>> for i in range(3):
	vals.append(getit())

	
Gimme!
righty'oh
Gimme!
I did
Gimme!
OK
 >>> vals
["righty'oh", 'I did', 'OK']
 >>>

HTH,

Brian vdB


More information about the Tutor mailing list