简体   繁体   中英

Repeating input to dictionary loop

"Create a dictionary whose keys are names and whose value for a key is a favorite food of the person with that name as follows: - The program should prompt for a name and favorite food and keep inputting names and favorite foods until the user enters an empty string for the name."

So far I have:

mydict=dict()
def favorite_food_name():
    name=input(str("name:"))
    food=input(str("food:"))
    mydict[name]=food       
    print(mydict)
favorite_food_name()

But I can't get the code to repeat in any kind of loop. What kind of loop would you use?

Use While True loop, and test value of name after its input.

By the way, some tips when coding:

  • you do not need str("name:") , since "name:" is str
  • if not necessary, put mydict in the function part, use return statement, do not use it as model level
  • you can do more to validate the input, here I call a strip function to remove typo of input.

Here is a sample code:

def favorite_food_name():
    mydict = dict()
    while True:
        name = input("name:")
        name = name.strip()
        if name == '':
            break
        food = input("food:")
        food = food.strip()
        mydict[name] = food
    # print(mydict)
    return mydict


if __name__ == '__main__':
    mydict = favorite_food_name()
    print(mydict)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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