Python 库中的变量内部函数

Python 库中的变量内部函数,python,python-3.x,Python,Python 3.x,我想从功能set\u word中更改u word。如何替换旧的单词,以便在菜单的下一次迭代中使用新单词 def main(): print("Welcome to the encrypt script") the_word = input("Enter the word you want to encrypt\n>>>") while True: #print("START") menu(the_word) def me

我想从功能
set\u word
中更改
u word
。如何替换旧的
单词
,以便在菜单的下一次迭代中使用新单词

def main():
    print("Welcome to the encrypt script")
    the_word = input("Enter the word you want to encrypt\n>>>")
    while True:
        #print("START")
        menu(the_word)

def menu(the_word):
    print("\n\n=============MENU=============")
    actions = {
    '1': ("Encrypt into templar's code", templar),
    '2': ("Encrypt with caesar's code", caesar),
    '3': ("Change the word", set_word),
    '4': ("Exit", stop)
    }

    for i in sorted(actions):
        print('{}. {}'.format(i, actions[i][0]))

    entry = input('Option: ')
    if entry in actions:
        try:
            actions[entry][1]()
        except:
            actions[entry][1](the_word)
    else:
        print("No such command") 

def templar(the_word):
    print("TEMPLAR",the_word) 

def caesar(the_word):
    print("CAESAR",the_word) 

def set_word():
    the_word = input("Enter the word you want to encrypt\n>>>")

def stop():
    print("Thanks for using the encrypt script")
    quit()

main()    

如果希望在程序中共享变量,则应将其声明为全局变量

在这种情况下,
变量应该声明为全局变量

在更改全局变量值的每个函数中,您应该在更改之前通过编写声明:
global\u单词

如果只读取变量,则不必声明
global\u单词

因此,您的代码可以更改为:

# declare the_word as global
the_word = ""


def main():
    global the_word
    print("Welcome to the encrypt script")
    the_word = input("Enter the word you want to encrypt\n>>>")
    while True:
        # print("START")
        menu()


def menu():
    global the_word
    print("\n\n=============MENU=============")
    actions = {
        '1': ("Encrypt into templar's code", templar),
        '2': ("Encrypt with caesar's code", caesar),
        '3': ("Change the word", set_word),
        '4': ("Exit", stop)
    }

    for i in sorted(actions):
        print('{}. {}'.format(i, actions[i][0]))

    entry = input('Option: ')
    if entry in actions:
        try:
            actions[entry][1]()
        except:
            actions[entry][1]()
    else:
        print("No such command")


def templar():
    print("TEMPLAR", the_word)


def caesar():
    print("CAESAR", the_word)


def set_word():
    global the_word
    the_word = input("Enter the word you want to encrypt\n>>>")


def stop():
    print("Thanks for using the encrypt script")
    quit()


main()

您可以让
设置单词()
返回新词,并在
菜单中为
设置单词()
指定调用结果。或者你可以把
这个词变成一个全局词,如果你愿意的话。或者创建一个类。“将调用菜单中的set_word()的结果分配给_word”我该怎么做?该函数在库中调用。“或创建一个类”我以前从未使用过类,也不应该使用。其中有多少是您的代码,有多少是在明显的家庭作业中给出的?这不是家庭作业xD,我还有时间。调用库的行是其他人写的,在stack上的另一篇文章中。我以前使用过globals,但每个人都告诉我不要这样做。我知道你应该避免它们,尤其是在大型项目中,所以我正试图避开它们。