Python:函数中int的-1

2024-04-24 10:15:14 发布

您现在位置:Python中文网/ 问答频道 /正文

如何从函数中的INT减去1?

这就是我想要的:

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()

Tags: 函数mainhaveusedintprinttrychoice
3条回答

如果之前没有定义生命,那么try: lives将始终引导您进入except部分。
如果在这段代码之前(通过给它赋值)或者在try部分中定义lives,那么您将看到-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()

**由Python2.7编写,对于Python3,打印需要括号。

您看到6的真正原因是因为抛出了NameError,因此您的else子句实际上从未执行过

NameError: name 'lives' is not defined

我只需要在函数外部定义变量,然后放置:

函数中的global lives

工作完成了。

相关问题 更多 >