代码对所有项目均运行相同

friends_dict = {'2018': ['tom','jerry','darryl'],'2017': ['john','cait','ash']}

print(friends_dict['2017'])
print(friends_dict['2018'])

find_Friend = input('What friend are you looking for? >>').strip()

flag = True

for year,friends in friends_dict.items():
    for friend in friends:
        if friend != find_Friend:
            flag = False
            break
        else:
            print('That\'s your friend homie!')

if not flag:
    add_friend = input('Would you like to add friend? (y/or any key to quit) >>').lower()
    if add_friend == 'y':
        ask_Year = input('What year would you like to add them to? >>').strip()
        if year in friends_dict.items() == ask_Year:
            friends_dict[ask_Year].append(find_Friend)

        else:
            friends_dict[ask_Year] = [find_Friend]

    else:
        print('Sounds good g! Have a good day.')        


print(friends_dict)

即使我将布尔标志设置为False,我的代码仍继续运行。我该如何解决?

a6733525 回答:代码对所有项目均运行相同

这是我发现的错误:

(a)。您仅将列表中的第一个元素与用户输入的值进行比较。您必须检查用户输入的find_Friend是否出现在整个列表中:

因此,用以下几行替换第一个for循环:

for year,friends in friends_dict.items():
    if find_Friend not in friends:
        flag = False
    else:
        flag = True

(b)。如果find_Friend在ANY列表中不存在,则您要求输入年份。您要做的就是检查year中是否存在friends_dict。由于year是该字典的关键,因此您只需使用in运算符即可查看ask_Year中是否存在输入值friends_dict。因此,将if not行替换为:

if not flag:
    add_friend = input('Would you like to add friend? (y/or any key to quit) >>').lower() 
    if add_friend == 'y':
        ask_Year = input('What year would you like to add them to? >>').strip()
        if ask_Year in friends_dict:
            friends_dict[ask_Year].append(find_Friend)
        else:
            friends_dict[ask_Year] = [find_Friend]
    else: print('Sounds good g! Have a good day.')
else: print('That\'s your friend homie!')
本文链接:https://www.f2er.com/3140275.html

大家都在问