How to restart a simple coin tossing game

百般思念 提交于 2019-12-01 14:20:22
user225312

Use a continue statement at the point which you want the loop to be restarted. Like you are using break for breaking from the loop, the continue statement will restart the loop.

Not based on your question, but how to use continue:

while True: 
        choice = raw_input('What do you want? ')
        if choice == 'restart':
                continue
        else:
                break

print 'Break!' 

Also:

choice = 'restart';

while choice == 'restart': 
        choice = raw_input('What do you want? ')

print 'Break!' 

Output :

What do you want? restart
What do you want? break
Break!

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

You need to use random.seed to initialize the random number generator. If you call it with the same value each time, the values from random.choice will repeat themselves.

After you enter 'y', guess == 0 will never be True.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!