Python Document Writer Error

57 views Asked by At

I am creating a simple document writer system in python that runs in the IDLE. This is the source code:

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

When I run the program in IDLE for the first time and give the input 1 suggesting I want the program to return "No Saved Documents" it returns the following error:

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

How can I fix this error? Thanks in advance!

1

There are 1 answers

1
Henry Zhu On

From looking at your code, you never initialized the variable n in the first place.

You need to define n first.

global n
n = 1

I think it would be a better practice to define the variable outside the function, and then reference it with global inside the function.

n = 1

def open():
    global n

Credit to @dshort: You can pass n in the function to avoid global variables declaration.