即使我给出了错误的答案,我的程序仍然给我积分

时间:2017-04-30 11:55:35

标签: python

我的程序一直让我永远继续,即使我没有把它弄好,除非我输入一个大于3的数字。

如果你尝试我的代码,你会明白我的意思:

#Ghost Game

while True:

    print ('Welcome To...') 
    from random import randint
    print ('Ghost Game') 
    feeling_brave = True
    score = 0
    while feeling_brave:
        ghost_door = randint(1,3)
        print('Three doors ahead...')
        print('A ghost behind one.')
        print('which door do you open?')
        door = input('1,2 or 3')
        door_num = int(door)
        if door_num == ghost_door:
            print('GHOST!')
            feeling_brave = False
        if door_num > 3:
            print('GHOST!')
            feeling_brave = False
        else:
            print('No Ghost')
            print('You enter the next room...')
            score = score + 1
    print('Run away!')
    print('GAME OVER YOU SCORED', score)

1 个答案:

答案 0 :(得分:1)

您需要使用elif而不是第二个if

if door_num == ghost_door:
    print('GHOST!')
    feeling_brave = False
elif door_num > 3:
    print('GHOST!')
    feeling_brave = False
else:
    print('No Ghost')
    print('You enter the next room...')
    score = score + 1

如果else不大于3,则if执行<{1}}第一次door_num测试

if是一个语句,附加了可选的elifelse块; Python将始终执行最多一个附加的块(否则将else。)

通过使用两个单独的 if语句,第二个if要求Python执行两个块中的一个;当GHOST大于3时打印door_num,或者提高分数,