"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:
str("name:")
, since "name:"
is str
mydict
in the function part, use return
statement, do not use it as model level 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.