【问题标题】:Python raw_input to extract from dictionaryPython raw_input 从字典中提取
【发布时间】:2019-03-02 13:23:49
【问题描述】:

我正在尝试实现一个解决方案,在该解决方案中,我调用 displayPerson() 来获取用户输入的 ID 号,并为用户打印信息。我应该注意,我正在从 Internet 下载一个包含这种格式数据的 csv 文件:

身份证、姓名、生日
1,杰克·斯派洛,2000 年 9 月 20 日

我的目标是从用户那里获取一个号码,该号码将查找并显示 ID。我希望提示继续显示并要求用户输入一个数字,直到他们输入负数或 0 退出。

    loop= True
    while loop== True:
        prompt = int(raw_input(" Enter ID of person you would like to search for: "))
        break

    if prompt >0:

        displayPerson(prompt,persons)


    else:
        print("Terminated.")

就目前而言,如果用户输入一个介于 1-100 之间的正数,我可以得到正确的输出,但是当我希望它向用户询问另一个数字时程序会停止,我无法理解如何这样做,它会给用户一条消息,让用户输入另一个小于 101 的数字(而不是给我一个 KeyError),显示数据,然后要求另一个数字。如果用户输入零,它会给出“终止”消息,然后停止,但我发现很难做其他任何事情。

这里是 displayPerson() 函数供参考:

def displayPerson(id, personDataDictionary):
    """

    :param id:
    :param personDataDictionary: Look at displayPerson in __name__ function. But I thought bday was pieces[2].
    :return:
    """
    print("id = {}, name = {}, birthday = {}".format(id, personDataDictionary[id][0],
                                                     personDataDictionary[id][1].strftime("%Y-%m-%d")))

【问题讨论】:

  • 顶部while循环的目的是什么?
  • 顶部的 while 循环是我尝试让提示在用户能够显示一个有效数字的结果后连续运行。我意识到这被“打破”打败了,但那是我的意图。

标签: python dictionary while-loop conditional


【解决方案1】:

解决方案

while True:
    prompt = int(raw_input(" Enter ID of person you would like to search for: "))

    if prompt > 100:
        print("Please try again")
        continue 
    elif prompt < 1: 
        displayPerson(prompt,persons)
    else:
        break

print("Terminated.")

说明

您进入循环并从用户那里获得一个 ID。

如果prompt &gt; 0:显示此人
否则,跳出循环并打印“终止”。

【讨论】:

  • 有没有办法使用它并将输入的另一个条件设置为
  • 已编辑解决方案。我强烈建议回到书籍和/或一些在线代码教师平台。
猜你喜欢
  • 1970-01-01
  • 2017-02-09
  • 2020-09-23
  • 2019-08-12
  • 2022-01-25
  • 2021-09-03
  • 1970-01-01
  • 1970-01-01
  • 2022-08-02
相关资源
最近更新 更多