首页 > 解决方案 > Python Heads or Tails 游戏,除了子句不显示

问题描述

我目前正在开发正面或反面游戏。所以它循环直到运行状况达到 0,但是当它达到 0 时,它假设打破了 try except 循环。但是当它走到最后时,它只会显示“可悲的是,那不是右侧!” 然后就停下来......不知道为什么非常感谢任何帮助。

代码:

import random

global health

try:
    global health
    health = 3
    while health != 0:
        print ("Pick a side of the coin. Heads or Tails?")
        print ("Your health is:", health)
        input_coin = input()
        input_coin = input_coin.lower()
        coin = random.choice(["heads", "tails"])

        if input_coin == coin:
            print ("You picked the right side!")
            health = health + 1
            continue
        elif health == 0:
            break
        else:
            print ("Sadly, that is not the right side!")
            health = health - 1
            continue
except:
    print("Youve run out of lives!")

标签: pythonpython-3.x

解决方案


要在健康达到零时显示消息,只需在循环中添加一个else子句。while

循环用于try except捕获错误,您的代码不会引发任何错误。

这将做你想要的。

import random

health = 3

while health != 0:
    print ("Pick a side of the coin. Heads or Tails?")
    print ("Your health is:", health)
    input_coin = input()
    input_coin = input_coin.lower()
    coin = random.choice(["heads", "tails"])

    if input_coin == coin:
        print ("You picked the right side!")
        health = health + 1
        continue
    elif health == 0:
        break
    else:
        print ("Sadly, that is not the right side!")
        health = health - 1
        continue
else:    
    print("You’ve run out of lives!")

推荐阅读