我目前正在从事“正面或反面”游戏。因此,它会循环运行,直到运行状况变为0,但当其变为0时,它会中断尝试try循环。但是到最后,它只会显示“可悲的是,那不是右边!”然后停下来...不知道为什么会有很大的帮助。
代码:
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!")
答案 0 :(得分:0)
要使运行状况达到零时显示此消息,只需在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!")