Skip to content Skip to sidebar Skip to footer

How To Restart A Simple Coin Tossing Game

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 'You may press q to quit at an

Solution 1:

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':
                continueelse:
                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!

Solution 2:

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 = 5defplayGame():
    remaining = GUESSES
    correct = 0while remaining>0:
        hiddenValue = random.choice(('heads','tails'))
        person = raw_input('Heads or Tails?').lower()

        if person in ('q','quit','e','exit','bye'):
            print('Quitter!')
            breakelif hiddenValue=='heads'and person in ('h','head','heads'):
            print('Correct!')
            correct += 1elif hiddenValue=='tails'and person in ('t','tail','tails'):
            print('Correct!')
            correct += 1else:
            print('Nope, sorry...')
            remaining -= 1print('You got {0} correct (out of {1})\n'.format(correct, correct+GUESSES-remaining))

defmain():
    print("You may press q to quit at any time")
    print("You have {0} chances".format(GUESSES))

    whileTrue:
        playGame()
        again = raw_input('Play again? (Y/n)').lower()
        if again in ('n','no','q','quit','e','exit','bye'):
            break

Solution 3:

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.

Solution 4:

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

Post a Comment for "How To Restart A Simple Coin Tossing Game"