Reputation: 1
How do I make it so that if the input is '!', it does not wait for the valueInput and immediately prints the dictionary?
itemInput = input()
valueInput = int(input())
while itemInput != '!':
if itemInput in groceryDict.keys():
groceryDict[itemInput] += valueInput
else:
groceryDict[itemInput] = valueInput
itemInput = input()
valueInput = int(input())
else:
print(groceryDict)
for example, if someone is done entering their list, they would enter '!', but the dict wouldn't print as it is waiting to ask for the valueInput again, and the user would have to enter a value before the dict prints. So where would I properly put the valueInput and the itemInput prompt in my code?
Upvotes: 0
Views: 113
Reputation: 71
A break
may be of help:
if itemInput == '!':
print(groceryDict)
break
Upvotes: 0
Reputation: 32
You can try the following:
groceryDict = {}
while True:
itemInput = input("Enter Item:")
if itemInput == "!":
break
valueInput = int(input("Enter Value for Item:"))
if itemInput in groceryDict.keys():
groceryDict[itemInput] += valueInput
else:
groceryDict[itemInput] = valueInput
print(groceryDict)
The loop will contines until the if statement becomes True
and the break
leads to ending it.
Next place the if statement directly behind the input for the item. This way the user must no longer enter a value befor the loop ends.
And be smart to the user, tell him/her/it what to enter. ;-)
Upvotes: 0
Reputation: 1545
Just break
itemInput = input()
valueInput = int(input())
while True:
if itemInput in groceryDict.keys():
groceryDict[itemInput] += valueInput
else:
groceryDict[itemInput] = valueInput
itemInput = input()
if itemInput == '!':
print(groceryDict)
break
valueInput = int(input())
Upvotes: 0
Reputation: 148890
You should only input a value after controlling the item name:
itemInput = input()
while itemInput != '!':
valueInput = int(input())
if itemInput in groceryDict.keys():
groceryDict[itemInput] += valueInput
else:
groceryDict[itemInput] = valueInput
itemInput = input()
print(groceryDict)
Or to have only one input for items:
itemInput = input()
while True:
itemInput = input().strip() # ignore leading or ending blank characters
if itemInput == '!': break
valueInput = int(input())
if itemInput in groceryDict.keys():
groceryDict[itemInput] += valueInput
else:
groceryDict[itemInput] = valueInput
print(groceryDict)
Upvotes: 1