我正在尝试编写一个菜单,其中选项1将给字典添加key:value对,而选项2将使用字典中的项运行线程模块。键是来自用户输入的消息,值是来自用户输入的线程在显示消息之前应暂停的秒数。
虽然线程本身现在不相关。我正在努力的事实是,当我将函数用于选项1时,它将成功将key:value对添加到字典中(称为messages_and_times)。但是,一旦函数完成,字典又又变空了,从选项2的函数可以看到,该字典可以访问它。
在底部,您可以看到我的代码。我添加了以下几行,以便在每个步骤中检查字典中的内容:
print(dict(messages_and_times))
if not messages_and_times:
print("This dictionary is empty.")
else:
print("This dictionary contains items.")
但是,它似乎也无法正常工作。首先,它打印“此词典包含项目”。打印的字典是否为空。我的代码下面的第二部分(clear()用于清除终端显示):
def create_dictionary():
clear()
answer = input(
"Would you like to add another message? (yes/no)").lower()
if answer == "yes":
option_1()
elif answer == "no":
clear()
print("You will now be returned to the main menu.")
print(dict(messages_and_times))
如果选择添加项目,则不会打印包含项目的字典。但是如果我添加线
print(dict(messages_and_times))
对main_menu()本身,上述create_dictionary()函数将打印一个空字典。只是main_menu()中的这一print()语句会影响create_dictionary()是否显示其中包含项目的字典。
有人可以帮我理解如何设计一种代码,其中词典保留一个功能创建的项目,以便其他功能可以访问它们吗?
提前感谢您的时间和帮助,
import os
clear = lambda: os.system('cls')
def main_menu():
list_of_messages = []
list_of_times = []
messages_and_times = zip(list_of_messages, list_of_times)
def option_1():
clear()
list_of_messages.append(
input("Please type in a message you would like to add to the list:"))
clear()
list_of_times.append(
input("Please type in the time of delay for this message:"))
def create_dictionary():
clear()
answer = input(
"Would you like to add another message? (yes/no)").lower()
if answer == "yes":
option_1()
elif answer == "no":
clear()
print("You will now be returned to the main menu.")
print(dict(messages_and_times))
if not messages_and_times:
print("This dictionary is empty.")
else:
print("This dictionary contains items.")
time.sleep(1.5)
main_menu()
else:
clear()
print("Please answer yes or no.")
time.sleep(1.5)
create_dictionary()
create_dictionary()
def option_2():
clear()
print(dict(messages_and_times))
if not messages_and_times:
print("This dictionary is empty.")
else:
print("This dictionary contains items.")
time.sleep(5)
main_menu()
clear()
selection = 0
while selection == 0:
print(("-" * 15) + "MAIN MENU" + ("-" * 15) + "\n")
print("1: Input a message and a corresponding time of delay before its display.")
print("2: Print your customized list of messages.")
print("3: Generate a list of random messages with random delays.\n")
selection = int(input(
"Please select one of the options, by typing in the corresponding number:"))
if selection == 1:
option_1()
elif selection == 2:
option_2()
elif selection == 3:
clear()
print("You've selected the third option.")
else:
clear()
print("Please select from options 1 - 3.\n")
time.sleep(1.5)
main_menu()