你如何在函数中减去一个INT?
这就是我正在尝试的:
try:
lives
except NameError:
lives = 6
else:
lives = lives-1
print("\nWrong!\nYou have " +str(lives)+ " lives remaining\n")
但它不起作用。
生命总是在6 :(
有什么想法吗?
更新:
def main():
used = []
print(blanks)
choice = input("\nEnter a letter:")
lives -= 1
print("\nWrong!\nYou have " +str(lives)+ " lives remaining\n")
used.append(choice)
main()
答案 0 :(得分:2)
你看到6的真正原因是因为抛出了 NameError ,因此你的else子句永远不会被实际执行
NameError: name 'lives' is not defined
答案 1 :(得分:0)
如果以前没有定义生命,那么try: lives
将始终将您带到除了部分
如果您在此代码之前定义生命(通过分配它)或在try部分内部定义生命,您将看到-1在运行。
try:
lives = 1
except NameError:
lives = 6
else:
lives = lives-1
print lives
将输出0
以及:
lives = 1
try:
lives
except NameError:
lives = 6
else:
lives = lives-1
print lives
编辑:
对于你的评论,这里有一些示例代码,它们可以像你想要实现的那样,这是一个猜字母的游戏。希望这对你有帮助。
def main():
# The setup
right_answer = "a"
lives = 6
# The game
while lives > 0:
choice = raw_input("Enter a letter:")
if choice == right_answer:
print "yay, you win!"
break
else:
lives -= 1
print "nay, try again, you have", lives, "lives left"
else:
print "you lose"
# This will call our function and run the game
if __name__ == "__main__":
main()
**写于python 2.7,对于python 3,打印将需要括号。
答案 2 :(得分:0)
我需要做的就是在函数外部定义变量,然后输入:
函数中的 global lives
。
完成工作。