Automate the Boring Stuff的示例程序未按说明工作



我一直在网上闲逛,但在任何地方都没有看到这件事,所以这一定是我做过的事情,但我不确定是什么。

《用Python自动处理无聊的东西》一书使用以下代码来解释词典:

birthdays = {'Alice': 'Apr 1', 'Bob': 'Dec 12', 'Carol': 'Mar 4'}
while True:
print('Enter a name: (blank to quit)')
name = input()
if name == '':
break
if name in birthdays:
print(birthdays[name] + ' is the birthday of ' + name)
else:
print('I do not have birthday information for ' + name)
print('What is their birthday?')
bday = input()
birthdays[name] = bday
print('Birthday database updated.')

这个代码不会为我生成任何错误,但当我运行它时,当我试图在dict中输入其中一个名字时,它没有返回任何信息。如果我什么都没输入,程序会反应为"我没有生日信息,他们的生日是什么?">

我试着用以下方式调整代码:

birthdays = {'Alice': 'Apr 1', 'Bob': 'Dec 12', 'Carol': 'Mar 4'}
while True:
print('Enter a name: (blank to quit)')
name = input()
if name == '':
break
if name in birthdays:
print(birthdays[name] + ' is the birthday of ' + name)
else:
print('I do not have birthday information for ' + name)
print('What is their birthday?')
bday = input()
birthdays[name] = bday
print('Birthday database updated.')

现在我可以输入现有的名称并获得正确的结果,但如果我输入的名称不在字典中,它将不返回任何内容,并再次告诉我输入名称。

显然,这只是一个例子,我明白它应该做什么,但它为什么要这样做?

birthdays[name] = bday

这一行是第二个代码块之后的问题。你必须用新的值更新字典中的值。在您的示例中,您将bday分配给一个应该已经在字典中的名称。

编辑:

birthdays = {'Alice': 'Apr 1', 'Bob': 'Dec 12', 'Carol': 'Mar 4'}
while True:
print('Enter a name: (blank to quit)')
name = input()
if name == '':
break
if name in birthdays:
print(name + ' birthday is ' + birthdays[name])
else:
print('I do not have birthday information for ' + name)
print('What is their birthday?(ex: Apr 4): ')
bday = input()
birthdays.update({name: bday})
print('Birthday database updated.')
print(birthdays)

我的钱在if/else的else块上,而不是像if一样缩进。这是我能够重现您描述的行为的唯一方法:

birthdays = {'Alice': 'Apr 1', 'Bob': 'Dec 12', 'Carol': 'Mar 4'}
while True:
print('Enter a name: (blank to quit)')
name = input()
if name == '':
break
if name in birthdays:
print(birthdays[name] + ' is the birthday of ' + name)
# Notice the else corresponds to "while", not the above "if".
else:
print('I do not have birthday information for ' + name)
print('What is their birthday?')
bday = input()
birthdays[name] = bday
print('Birthday database updated.')

请注意,这实际上是有效的Python,如果while在没有break语句的情况下退出,则会输入else子句。

例如:

while 1 != 1:
pass
else:
print("Got to else.")

输出:

Got to else.

最新更新