【发布时间】:2021-03-15 22:39:46
【问题描述】:
我正在编写我的第一个 python 编程。我没有PC编程经验。我在函数中使用全局变量时遇到问题。所以我重新定义了它们。
这是我定义全局变量的程序顶部。
#Define Global Variables
segments = []
highscore = 0
currentscore = 0
delay = 0.2
level = 1
这是我使用它们的功能之一。一切正常,但这被认为是不好的做法吗?我应该将它们作为参数传递吗?只是想知道最好的过程是什么。我不想发布完整的代码,因为它只有 200 多行而且运行良好。
def gameover():
global highscore
global currentscore
global delay
global level
time.sleep(1)
if currentscore >= highscore:
highscore = currentscore
sethighscore()
currentscore = 0
head.goto(0,0)
head.direction = "stop"
for index in range(len(segments)):
x = 1000
y = 1000
segments[index].goto(x,y)
segments.clear()
delay = 0.2
level = 1
【问题讨论】:
-
我认为当你想改变全局变量时,你只需要 global 关键字。在学校里,我被教导要把全局变量和常量都大写。
-
这看起来更适合Code Review
-
@buran 在建议用户在 CR 上发帖时,如果还有类似“请阅读相关帮助中心页面,例如 'What topics can I ask about here?' 和 'How do I ask a good question?”。在当前形式中,上面的代码可能会因为缺少上下文而被关闭 - CR has an increased post size limit,因此用户可以提供足够的上下文。
标签: python python-3.x variables global-variables local-variables