示例程序从自动化无聊的东西不工作的描述

2024-06-08 04:19:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在互联网上闲逛,但没有看到任何地方,所以这一定是我做了什么,但我不知道是什么。你知道吗

本书使用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.')

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

显然这只是一个例子,我知道它应该做什么,但它为什么要这样做?你知道吗


Tags: 代码name名称inputif字典isapr
2条回答
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)

我的钱在else块上,因为if/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.

相关问题 更多 >

    热门问题