python-3.x - 为什么这只是在运行一个函数后停止,为什么这个变量不上去?
问题描述
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()
。
我刚开始编程,非常感谢批评。
解决方案
variables和inside 函数是这些函数的局部变量deathcounter
,它们与您在第一行中定义的变量不同。因此,对和中的任何这些变量所做的更改都不会反映到全局变量中。如果您希望更改反映在全局范围内,那么您应该使用关键字。n
r
gamestart
gameover
gamestart
gameover
global
您可以在此处阅读有关全局变量的信息: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()
推荐阅读
- python - 开始急切执行时的非法指令(核心转储)
- java - 使用 JAXB/XJC 插件时出现无法识别的参数 -XsomePlugin 错误
- vba - 按换行符 VBA 拆分单元格
- html - Bootstrap 4 和全长 hr 列
- javascript - Node js需要来自html正文的数据
- c# - EF Core Find方法等效于多条记录?
- ios - 从单元格中分离并解析对象不起作用
- c++ - 使用 Optix 5 显示 X 粒子
- java - Android - 未及时为类变量分配 setOnItemSelectedListener 的值
- php - 如何检查laravel中的变量是否为空?