如何在函数之前定义一个全局变量,然后在python的函数中引用它?

2024-10-05 18:10:17 发布

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

我刚熟悉了图灵机器。我正在制作一个半精确的虚拟图灵机,但我遇到了一个看似简单的问题,我只知道有一个解决方案。我在网上研究了一下,但没有找到任何能满足我的问题。你知道吗

如何使变量“l”在函数中可调用。它必须是可调用的,因为如果我在函数中定义变量的初始值,当函数循环时,它会将值重置为0。你知道吗

这是我的密码:

blanktape = []
for x in range(1,251):
    x = ' '
    blanktape.append(x)

global l
l = 1
non = ' '
head = blanktape[l]
symbols = [3, 'ee', 'x']

def mconfigb():
    if head == non:
        blanktape[blanktape.index(head)] = 0
        l = l + 2

def mconfigc():
    if head == non:
        blanktape[blanktape.index(head)] = 1
        l = l + 2

def turingmachine():
        while l < len(blanktape) + 1:
            mconfigb()
            mconfigc()
        return blanktape

print turingmachine()

Tags: 函数indexif定义def解决方案head重置
3条回答
def mconfigb():
     global l

其他函数也可以这样做。你知道吗

def function(input):
    global globvar
    ....

它们必须按函数声明。但是,我认为您应该将所有创建的内容打包到turingmachine类中,并使用实例变量。你知道吗

你需要把:

global l

函数本身中(您可能需要重新考虑变量命名约定,l不是一个好名字)。你知道吗

例如:

xyzzy = 1

def fn():
    global xyzzy
    xyzzy = xyzzy + 1

相关问题 更多 >