簡體   English   中英

Python raw_input 從字典中提取

[英]Python raw_input to extract from dictionary

我正在嘗試實現一個解決方案,在該解決方案中我調用 displayPerson(),該解決方案接受用戶輸入的 ID 號,並為用戶打印信息。 我應該注意,我正在從 Internet 下載一個包含以下格式數據的 csv 文件:

身份證、姓名、生日
1,傑克斯派洛,09/20/2000

我的目標是從用戶那里獲取一個數字,該數字將查找並顯示 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 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 > 0 :顯示人物
否則,跳出循環並打印“已終止”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM