Python文档编写器

2024-04-25 23:05:03 发布

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

我正在用python创建一个在空闲环境下运行的简单文档编写器系统。这是源代码:

    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()

当我第一次在空闲状态下运行程序时,输入1表示我希望程序返回“No Saved Documents”,它返回以下错误:

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

如何修复此错误? 提前谢谢!你知道吗


Tags: runtextinputrawiftitlesavedef
1条回答
网友
1楼 · 发布于 2024-04-25 23:05:03

从你的代码来看,你从来没有把变量n放在第一位。你知道吗

你需要先定义n。你知道吗

global n
n = 1

我认为更好的做法是在function之外定义变量,然后在function内部用global引用它。你知道吗

n = 1

def open():
    global n

记入@dshort: 可以在函数中传递n以避免global变量声明。你知道吗

相关问题 更多 >