首页 > 解决方案 > 为什么这只是在运行一个函数后停止,为什么这个变量不上去?

问题描述

deathcounter, r, n, deaths=0, 0, 0, 0
def gamestart():
    print("Enter the cheese world?")
    print("(1) Yes (2) No")
    n=int(input(""))
def gameover():
    print("GAME OVER")
    deathcounter=deaths+1
    n=0
    r=0
    gamestart()
print("Deaths :", deathcounter)
gamestart()
if n == 1:
    print("You enter the cheese world. It's full of cheese.")
    print("(1) Eat the cheese (2) Banish the cheese")
    r=int(input(""))
if n == 2:
    print("You reject the cheese world. What is the point anymore.")
    gameover()
if r == 1:
    print("You eat the cheese. You die from an artery blockage.")
    gameover()
if r == 2:
    print("You attempt to banish the cheese. The cheese's power is incomprehensible to you, and you lose your mind.")
    gameover()

我不明白为什么这会打印gamestart()然后停止,为什么deathcounter在运行后不上升gameover()

我刚开始编程,非常感谢批评。

标签: python-3.x

解决方案


variables和inside 函数是这些函数的局部变量deathcounter,它们与您在第一行中定义的变量不同。因此,对和中的任何这些变量所做的更改都不会反映到全局变量中。如果您希望更改反映在全局范围内,那么您应该使用关键字。nrgamestartgameovergamestartgameoverglobal

您可以在此处阅读有关全局变量的信息:https ://www.geeksforgeeks.org/global-local-variables-python/

使用global关键字后的代码:

deathcounter, r, n, deaths=0, 0, 0, 0

def gamestart():
    global n
    print("Enter the cheese world?")
    print("(1) Yes (2) No")
    n=int(input(""))

def gameover():
    global n, r, deathcounter
    print("GAME OVER")
    deathcounter=deaths+1
    n=0
    r=0
    gamestart()

print("Deaths :", deathcounter)
gamestart()
if n == 1:
    print("You enter the cheese world. It's full of cheese.")
    print("(1) Eat the cheese (2) Banish the cheese")
    r=int(input(""))
if n == 2:
    print("You reject the cheese world. What is the point anymore.")
    gameover()
if r == 1:
    print("You eat the cheese. You die from an artery blockage.")
    gameover()
if r == 2:
    print("You attempt to banish the cheese. The cheese's power is incomprehensible to you, and you lose your mind.")
    gameover()

推荐阅读