【发布时间】:2022-09-22 22:38:00
【问题描述】:
我正在从 Eric Matthes 的《Python Crash Course》一书中学习,他的字典循环解决方案并没有像他声称的那样工作。
这是我需要做的:
#looping through dicitionary with names of people and their favorite programming language.
#if name matches one of my friends, we will display a message about their favorite language.
#it prints only Phil. Why???
favorite_languages = {\'jen\': \'python\',\'sarah\': \'c\',\'edward\': \'ruby\',\'phil\': \'python\'}
friend = [\'phil\', \'jen\', \'jakub\']
for name in favorite_languages.keys():
print(name)
if name in friend:
print(\" Hi \" + name.title() +
\", I see your favorite language is \" +
favorite_languages[name].title() + \"!\")
-
因为你的缩进是错误的。
if不在for循环中。 -
从 python 3.6 开始,我建议使用
f-strings:尝试print(f\"Hi {name.title()}, I see your favorite language is {favorite_languages[name].title()}!\")当然在你修复缩进问题之后
标签: python dictionary