我正在用 python 创建一个在 IDLE 中运行的简单文档编写器系统。这是源代码:
def openn():
global n
if n==1:
print("[1] - " + title)
print("[2] - Exit")
option=raw_input()
if int(option)==1:
print(text)
print("type 'done' when done")
do=raw_input()
if do=='done':
run()
if do!='done':
run()
if n==0:
print("No Saved Documents")
def new():
print("Enter a title:")
global title
title=raw_input()
print(str(title) + ":")
global text
text=raw_input()
print("[1] - Save")
print("[2] - Trash")
global n
global save
save=input()
if save==1:
n=1
run()
if save==2:
n=0
run()
def run():
print("[1] - Open a saved document")
print("[2] - Create a new saved document")
global save
save=1
global choice
choice = input()
if choice==1:
openn()
if choice==2:
new()
run()
当我第一次在 IDLE 中运行程序并给出输入 1 时,表明我希望程序返回“无保存的文档”,它返回以下错误:
File "/Users/tylerrutherford/Documents/Python Programs/Operating Systen Project/document_writer.py", line 5, in openn
if n==1:
NameError: global name 'n' is not defined
如何修复此错误? 提前致谢!
最佳答案
从代码来看,您一开始就没有初始化
变量 n。
您需要先定义n。
global n
n = 1
我认为在函数
外部定义变量,然后在函数
内部使用global
引用它是更好的做法。
n = 1
def open():
global n
感谢@dshort:
您可以在函数中传递 n 以避免全局
变量声明。
关于Python 文档编写器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30769101/