How to restart a simple coin tossing game

前端 未结 4 1653
面向向阳花
面向向阳花 2021-01-16 16:43

I am using python 2.6.6

I am simply trying to restart the program based on user input from the very beginning. thanks

import random
import time
print         


        
4条回答
  •  孤城傲影
    2021-01-16 17:30

    I recommend:

    1. Factoring your code into functions; it makes it a lot more readable
    2. Using helpful variable names
    3. Not consuming your constants (after the first time through your code, how do you know how many guesses to start with?)

    .

    import random
    import time
    
    GUESSES = 5
    
    def playGame():
        remaining = GUESSES
        correct = 0
    
        while remaining>0:
            hiddenValue = random.choice(('heads','tails'))
            person = raw_input('Heads or Tails?').lower()
    
            if person in ('q','quit','e','exit','bye'):
                print('Quitter!')
                break
            elif hiddenValue=='heads' and person in ('h','head','heads'):
                print('Correct!')
                correct += 1
            elif hiddenValue=='tails' and person in ('t','tail','tails'):
                print('Correct!')
                correct += 1
            else:
                print('Nope, sorry...')
                remaining -= 1
    
        print('You got {0} correct (out of {1})\n'.format(correct, correct+GUESSES-remaining))
    
    def main():
        print("You may press q to quit at any time")
        print("You have {0} chances".format(GUESSES))
    
        while True:
            playGame()
            again = raw_input('Play again? (Y/n)').lower()
            if again in ('n','no','q','quit','e','exit','bye'):
                break
    

提交回复
热议问题