Python 2.7 Coin Flip程序每次都崩溃

时间:2014-12-09 05:57:37

标签: python-2.7 coin-flipping

我有一个简单的硬币翻转程序这个奇怪的问题,而不是给我一些错误,每当我运行这个代码时,它只是崩溃。我键入是或否答案并按Enter键,但它什么也没做。然后我再次点击进入,它完全关闭。

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 个答案:

答案 0 :(得分:0)

由于您只是忽略了raw_input方法的返回值,因此您不知道用户输入的内容是为了摆脱循环。

以下是程序的简化版本,请注意我如何将raw_input方法的结果存储在result中并使用它来控制执行循环:

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!')