so I have a question regarding dictionaries in Python.
I’d like to create a dictionary where the user will be prompted with 2 options; either updating the dictionary or clearing the dictionary.
Let me first show you my code:
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()
Now here’s what I’d like to add:
1.The ability for the user to keep updating the dictionary (which means that if someone input 10 apples, the dictionary will store 10 apples and the user will be prompted again to input the number of apples he want to input to update the dictionary).
I’m not really sure how to implement a loop into this.
2, The ability for the user to clear his dictionary after updating it. For example: if someone inputs 10 apples, the loop will ask the user again if he/she would like to clear the dictionary.
It’s kind of like a bank where someone deposits money and clears their account if they don’t have any money left in there account.
With what you are doing, it might be better to create your own class. You should also have different functions for all of the different actions you wish to do. ie. Update, Clear, Add
You should also look in to using
tryandexceptstatements to make sure the program does not crash if the wrong input is used. Also you should add in an exit command to exit the program, otherwise this will loop forever. for example. if the user input is “exit” then have a conditional notice it andbreak.