我想从函数the_word
更改set_word
。如何替换旧的the_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()
答案 0 :(得分:0)
如果您希望在程序中共享变量,则应将其声明为全局变量。
在这种情况下,the_word
变量应声明为全局。
在更改全局变量值的每个函数中,您应该在更改之前通过写入来声明它:global the_word
如果您只阅读变量,则不必声明global the_word
因此您的代码可以更改为:
# 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()