Python图灵机脚本报错:已赋值变量仍提示未定义(UnboundLocalError)
问题解决:UnboundLocalError 处理
核心原因
Python中,当函数内部存在对变量的赋值操作时,解释器会默认将该变量视为局部变量,即使全局作用域已定义同名变量。你的read()函数里有state = 2这类赋值语句,所以执行if state == 0时,解释器认为state是局部变量,但此时还未赋值,从而抛出错误。同理index变量也存在相同问题。
修复步骤
1. 声明全局变量
在涉及修改全局变量的函数开头,添加global声明,告诉解释器使用全局作用域的变量:
def MoveRight(): global index index += 1 def MoveLeft(): global index index -= 1 def read(): global state, index, tape # 原函数逻辑不变
2. 修复未调用的函数
代码中有几处仅写了MoveRight或MoveLeft,未加括号调用,导致函数不会执行,需补充括号:
- 将
MoveRight改为MoveRight() - 将
MoveLeft改为MoveLeft()
3. 优化逻辑(可选)
原read()函数存在重复的状态判断(如两次if state ==4),可能导致逻辑冲突,建议改用elif来确保同一状态下仅触发一个分支:
def read(): global state, index, tape if state == 0: if tape[index] == 0: tape.insert(index, "1") state = 2 MoveRight() read() elif state == 2: if tape[index] == 0: tape.insert(index, "1") state = 3 MoveRight() read() elif state == 3: if tape[index] == 0: tape.insert(index, "1") state = 4 MoveLeft() read() elif state == 4: if tape[index] == 1: tape.insert(index, "0") state = 4 MoveLeft() read() elif tape[index] == 0: tape.insert(index, "0") state = 5 MoveRight() read() elif state == 5: if tape[index] == 0: tape.insert(index, "0") state = 5 MoveRight() read() elif tape[index] == 1: tape.insert(index, "1") state = 0 MoveRight() read()
修复后的完整代码
#Turing Machine In Python #by adrian wheeler #the script index = 5 state = 0 tape = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] def MoveRight(): global index index += 1 def MoveLeft(): global index index -= 1 def read(): global state, index, tape if state == 0: if tape[index] == 0: tape.insert(index, "1") state = 2 MoveRight() read() elif state == 2: if tape[index] == 0: tape.insert(index, "1") state = 3 MoveRight() read() elif state == 3: if tape[index] == 0: tape.insert(index, "1") state = 4 MoveLeft() read() elif state == 4: if tape[index] == 1: tape.insert(index, "0") state = 4 MoveLeft() read() elif tape[index] == 0: tape.insert(index, "0") state = 5 MoveRight() read() elif state == 5: if tape[index] == 0: tape.insert(index, "0") state = 5 MoveRight() read() elif tape[index] == 1: tape.insert(index, "1") state = 0 MoveRight() read() #running the script read()
内容的提问来源于stack exchange,提问作者Adrian Wheeler
相关产品推荐
相关产品推荐

