首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Python Heads或Tails游戏,不显示except子句

Python Heads或Tails游戏,不显示except子句
EN

Stack Overflow用户
提问于 2018-06-21 05:55:18
回答 1查看 50关注 0票数 1

我目前正在开发一个头部或尾巴的游戏。所以它会循环,直到健康状态达到0,但当它达到0时,它会中断try except循环。但当它到达最后时,它只会显示“很遗憾,那不是右边!”然后就停下来..。不知道为什么任何帮助都是非常感谢的。

代码:

代码语言:javascript
复制
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!")
EN

回答 1

Stack Overflow用户

发布于 2018-06-21 07:01:27

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

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

这会做你想做的事。

代码语言:javascript
复制
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!")
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50957627

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档