Python 3.x 为什么在运行一个函数之后,这个变量就停止了,为什么这个变量没有上升?
我不明白为什么这会打印Python 3.x 为什么在运行一个函数之后,这个变量就停止了,为什么这个变量没有上升?,python-3.x,Python 3.x,我不明白为什么这会打印gamestart()然后停止,为什么deathcounter在运行gameover()后不会上升 我刚开始编程,所以非常感谢大家的批评。您需要将这些变量声明为全局内部函数 e、 g 函数内部的变量deathcounter、n和r是这些函数的局部变量,它们与第一行中定义的变量不同。因此,对gamestart和gameover中的任何变量所做的更改都不会反映到全局变量。如果希望更改反映在全局范围中,则应使用global关键字 您可以在此处阅读有关全局变量的内容: 使用glob
gamestart()
然后停止,为什么deathcounter
在运行gameover()
后不会上升
我刚开始编程,所以非常感谢大家的批评。您需要将这些变量声明为全局内部函数 e、 g
函数内部的变量
deathcounter
、n
和r
是这些函数的局部变量,它们与第一行中定义的变量不同。因此,对gamestart
和gameover
中的任何变量所做的更改都不会反映到全局变量。如果希望更改反映在全局范围中,则应使用global
关键字
您可以在此处阅读有关全局变量的内容:
使用global
关键字后的代码:
global n
# then
n=int(input(""))
帮助,但在第二次给出
n
后停止。已工作,但在第二次给出n后停止打印文本+1@jorma是的,程序中有一些逻辑错误。您可以在几分钟内发现这些问题。我在回答中没有提到这些问题,因为我只是在回答你的问题question@jorma提示:使用while循环
global n
# then
n=int(input(""))
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()