0

The program first asks the user if they'd like to load their own file or use the the file provided by the script.

filename=0
def first(filename):
    print('Please Select:')
    print('Run Program Now? Press "1"')
    start = int(input('Load Your Own List and Run Program? Press "2": '))

    if start ==1:
        global filename
        filename = 'file.txt'
    elif start ==2:
        import tkinter as tk
        from tkinter import filedialog

        root = tk.Tk()
        root.withdraw()
        global filename
        filename = tkinter.filedialog.askopenfilename()
    else:
        print("You didn't enter a valid selection!")
        first(filename)
    main()

I'm using another function which should call the correct file based on the user input.

def guess(real):
    WORDLIST = filename
    with open(WORDLIST, 'r') as in_file:

Error:

ErrorSyntaxError: name 'filename' is assigned to before global declaration

This all worked earlier when I had the user input and elif statements within

def guess(real):

Although I wanted to call it separately and that's why I have the user input in it's own function.

CYBORG
  • 104
  • 2
  • 4
  • 11

1 Answers1

1

You don't need to use return with global variables, however I would avoid using global variables if possible. You might want to read "why are global variables evil" for more details.

A simplified version of the code you provided is shown below using return and then passing the result to another function to avoid using global variables:

def first():
    while True:
        print('Please Select:')
        print('Run Program Now? Press "1"')
        start = int(input('Load Your Own List and Run Program? Press "2": '))

        if start == 1:
            filename = 'file.txt'
            return filename
        elif start == 2:
            filename = 'hello.txt'
            return filename
        else:
            print("You didn't enter a valid selection!")

def second(filename):
    print (filename)

filename = first()
second(filename)
Community
  • 1
  • 1
DavidG
  • 24,279
  • 14
  • 89
  • 82