所以我对Python中的字典有疑问。我想创建一个字典,其中将提示用户 2 个选项;更新字典或清除字典。首先让我向您展示我的代码:
def myStuff():
food = {'Apple': 0, 'Banana': 0, 'Grapes': 0}
choice = raw_input('Please pick an option:\n1) Update number of food I have\n2) Clear all\n>>')
if choice == str(1):
apple = int(raw_input('How many apples do you want to add?\n>>'))
banana = int(raw_input('How many bananas do you want to add?\n>>'))
grapes = int(raw_input('How many grapes do you want to add?\n>>'))
print 'Updating...'
food['Apple'] = apple
food['Banana'] = banana
food['Grapes'] = grapes
print food
elif choice == str(2):
food['Apple'] = 0
food['Banana'] = 0
food['Grapes'] = 0
print food
else:
return False
myStuff()
现在这是我想补充的:
1.用户不断更新字典的能力(也就是说如果有人输入10个苹果,字典将存储10个苹果,并再次提示用户输入他要输入的苹果数量来更新字典) . 我不太确定如何在其中实现循环。
2,用户在更新后可以清除他的字典的能力。例如:如果有人输入 10 个苹果,循环将再次询问用户是否要清除字典。
这有点像银行,有人存钱,如果账户里没有钱,就清空他们的账户。