[Tutor] Repeating a routine

Brian van den Broek broek at cc.umanitoba.ca
Thu Feb 23 05:09:23 CET 2006


John Connors said unto the world upon 22/02/06 07:59 PM:
> G'day,
> 
> I think my peanut sized brain is starting to understand how to do this. 

Glad you're making progress :-)  It's normal it takes a while to learn 
to adjust your thinking to a rigid and precise system.

I've made some pretty big changes and explained in comments. There are 
a couple of bumps up in level of Python-fu, so ask if it puzzles. 
Also, watch for the likely improvements on mine, too :-)  (I'm no 
expert, either.)

Also, I tend to have longer names than most people do. But I think it 
is important for understanding longer programs (even your own) that 
the names are well chosen.

<snip>

> import random
> 
> def dice():
>     return random.randint(1,6)
> 
> playagain = 'y'
> 
> while playagain == 'y':
> 
>     die1 = dice()
>     die2 = dice()
> 
>     print '1st dice is ',die1,'\n','2nd dice is ',die2
> 
>     die3 = dice()
>     die4 = dice()
>     winnum = die3 + die4
> 
>     print'combined total for the next 2 dice is ',winnum
> 
>     if winnum == 6:
>         print 'you win'
>     else:
>         print 'you lose'
> 
>     playagain = raw_input('play again? (y/n) ')
> 
> print 'goodbye'

import random

def die_roll():
     return random.randint(1,6)

# The while True / break construct avoids the dummy 'y' value
# in your version.
while True:

     # This assigns all the dice at once and makes a tuple from the
     # list comprehension. A tuple to make the string formatting happy.
     rolls = tuple([die_roll() for x in range(4)])

     # uses string formatting, a very powerful tool
     print '1st die is %s\n2nd die is %s' %(rolls[:2])

     turn_score = sum(rolls[2:])

     print 'combined total for the next 2 dice is %s' %turn_score

     if turn_score == 6:
         print 'you win'
     else:
         print 'you lose'

     playagain = raw_input('play again? (y/n) ')

     # .lower() to accommodate 'Y'. You might think about how to
     # handle 'yes' and the like.
     if playagain.lower() != 'y':
         break

print 'goodbye'

HTH,

Brian vdB


More information about the Tutor mailing list