3 回答
TA贡献1796条经验 获得超4个赞
你可以试试这个
for user in users:
if user in fav_food.keys():
print(user.capitalize(),"likes",fav_food[user].capitalize())
else:
print(user.capitalize(),"hasn't taken the poll")
这将输出为-
Jason likes Spaghetti
Phil hasn't taken the poll
Jen likes Pizza
Ben hasn't taken the poll
TA贡献1786条经验 获得超13个赞
你的意思是喜欢
for user in users:
try:
print('{} likes {}'.format(user, fav_food[user]))
except KeyError:
print("{} hasn't taken the poll".format(user))
这将遍历所有用户,如果特定用户没有最喜欢的食物,那么它只会打印您所说的内容。
TA贡献2012条经验 获得超12个赞
fav_food = {'jen':'pizza','eric':'burrito','jason':'spaghetti','tom':'mac'}
users = ['jason', 'phil', 'jen', 'ben']
for user in users:
print(f"{user} likes {fav_food[user]}" if fav_food.get(user, None) else f"{user} hasn't taken the poll yet")
像魅力一样工作,但值得记住的是,如果用户将空字符串作为他们最喜欢的食物,它会说他们没有参加投票
添加回答
举报