函数elifs中的多个全局语句

时间:2017-04-07 12:35:58

标签: python python-3.x global-variables

程序首先询问用户是否要加载自己的文件或使用脚本提供的文件。

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

我正在使用另一个根据用户输入调用正确文件的函数。

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

错误:

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

当我在

中有用户输入和elif语句时,这一切都工作得更早了
def guess(real):

虽然我想单独调用它,这就是为什么我有用户输入它自己的功能。

1 个答案:

答案 0 :(得分:1)

您不需要对全局变量使用return,但如果可能的话,我会避免使用全局变量。您可能需要阅读“why are global variables evil”了解更多详情。

您提供的代码的简化版本如下所示,使用return,然后将结果传递给另一个函数以避免使用全局变量:

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)