Python 2.7 Coin Flip Program Crashes Every Time

142 views Asked by At

I'm having this strange problem with a simple coin flip program where, instead of giving me some sort of error, whenever i run this code it just sort of crashes. I type in a yes or no answer and hit enter, but it does nothing. Then I hit enter again and it closes out completely.

import time
import random

constant = 1
FirstRun = True

def Intro():
    raw_input("Hello and welcome to the coin flip game. Do you wish to flip a coin? (yes or no): ")


def CoinToss():
    print "You flip the coin"
    time.sleep(1)
    print "and the result is..."
    time.sleep(1)
    result = random.randint(1,2)
    if result == 1:
        print "heads"
    if result == 2:
        print "tails"


while constant == 1:
    if FirstRun == True:
        Intro()
        FirstRun = False

    else:
        answer = raw_input()
        if answer == "yes":
            CoinToss()
            raw_input("Do you want to flip again? (yes or no): ")
        else:
            exit()
1

There are 1 answers

0
Burhan Khalid On

As you simply ignore the return value of the raw_input method, you don't know what the user is entered in order to break out of the loop.

Here is a simplified version of your program, note how I store the result of the raw_input method in result and use that to control the execution loop:

import random
import time

result = raw_input('Hello and welcome to the coin flip game. Do you wish to flip a coin? (yes or no): ')

while result != 'no':
    print('You flip the coin....')
    time.sleep(1)
    print('...and the result is...')
    toss_result = random.randint(1,2)
    if toss_result == 1:
        print('Heads')
    else:
        print('Tails')

    result = raw_input('Do you want to flip again? (yes or no): ')

print('Goodbye!')