简体   繁体   English

Python raw_input 从字典中提取

[英]Python raw_input to extract from dictionary

I am trying to implement a solution where I call the displayPerson() that takes the user input for an id number and will print the information for the user.我正在尝试实现一个解决方案,在该解决方案中我调用 displayPerson(),该解决方案接受用户输入的 ID 号,并为用户打印信息。 I should note that I'm downloading a csv file from the internet that contains data in this format:我应该注意,我正在从 Internet 下载一个包含以下格式数据的 csv 文件:

id, name , birthday身份证、姓名、生日
1, Jack Sparrow, 09/20/2000 1,杰克斯派洛,09/20/2000

My goal is to get a number from the user which will look up and display the ID.我的目标是从用户那里获取一个数字,该数字将查找并显示 ID。 I want the prompt to continue to show up and ask the user for a number until they enter a negative number or 0 to exit.我希望提示继续显示并要求用户输入一个数字,直到他们输入负数或 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.")

As it stands now, I am able to get the output correct if the user enters a positive digit between 1-100 but the program stops when I would like it to ask the user for another number and I can't fathom how to work this so that it will give the user a message to enter another number less than 101 (instead of giving me a KeyError), display the data, and then ask for another number.就目前而言,如果用户输入 1-100 之间的正数,我能够获得正确的输出,但是当我希望它向用户询问另一个数字时程序停止并且我无法理解如何工作这样它就会给用户一条消息,输入另一个小于 101 的数字(而不是给我一个 KeyError),显示数据,然后要求另一个数字。 If the user enters a zero it gives the "Terminated" message and then stops but I'm finding it hard to do anything else.如果用户输入零,它会给出“终止”消息,然后停止,但我发现很难做任何其他事情。

Here is the displayPerson() function for reference:这里是 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")))

Solution解决方案

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.")

Explanation解释

You enter the loop and get an ID from the user.您进入循环并从用户那里获得一个 ID。

If prompt > 0 : display the person如果prompt > 0 :显示人物
Otherwise, break out of the loop and print "Terminated".否则,跳出循环并打印“已终止”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM