Stack Overflow Asked by ShemTheUltimate on January 27, 2021
Here’s this program where a dictionary my_dictionary={“Potato”:12, “Onion”:16, “Ginger”:15, “Garlic”:12, “Tomato”:15
is given. Now I’ve to write a python program that takes the grocery names as input from the users and shows the total price of the groceries.
But with some exceptions to handle:
If the input is: Potato,Onion,Ginger The output should be: 43
And If the input is: Potato,Onion,Ginger,Beef The output should be: Some groceries are not available in the dictionary.
I tried this:
user_input = input("Enter grocery names: ")
user_input = user_input.split(',')
my_dictionary={"Potato":12, "Onion":16, "Ginger":15, "Garlic":12, "Tomato":15}
total_price = 0
try:
for items in user_input:
if items in my_dictionary.keys():
total_price = total_price + my_dictionary[items]
print(total_price)
except ValueError:
for items in user_input:
if items not in my_dictionary:
break
print("Some groceries are not avaiable in the dictionary.")
The output came:
Enter grocery names: Potato,Onion,Ginger,Beef
43
What should I do?
Solution for your question:
user_input = input("Enter grocery names: ")
user_input = user_input.split(',')
my_dictionary={"Potato":12, "Onion":16, "Ginger":15, "Garlic":12, "Tomato":15}
total_price = 0
for items in user_input:
try:
total_price = total_price + my_dictionary[items]
except:
total_price = "Some groceries are not avaiable in the dictionary."
break
print(total_price)
Prints Output as:
Enter grocery names: Potato,Onion,Ginger,Beef #Input
Some groceries are not avaiable in the dictionary. #Output
Correct answer by Anup Tiwari on January 27, 2021
You can define try/except structures like below.
user_input = input("Enter grocery names: ")
user_input = user_input.split(',')
my_dictionary={"Potato":12, "Onion":16, "Ginger":15, "Garlic":12, "Tomato":15}
total_price = 0
try:
for items in user_input:
total_price = total_price + my_dictionary[items]
print(total_price)
except:
print("Some groceries are not avaiable in the dictionary.")
If there's no key in my_dictionary, it makes an exception so it will print your error message.
Here's the result.
Enter grocery names: Potato,Onion,Ginger
43
Enter grocery names: Potato,Onion,Ginger,Beef
Some groceries are not avaiable in the dictionary.
Answered by ZaO Lover on January 27, 2021
Your approach is very close, but the issue is that the following line prevents your try-block from raising an exception, so you never trigger the except block since the if statement causes missing groceries to be skipped, without raising an exception.
if items in my_dictionary.keys():
There are two ways you can alter to get to your desired behavior.
1 Removing 'if statement' for try block
You actally also need to check for 'KeyError' since this is what will be raised when getting value for a non-existent dictionary key.
def get_groceries_price(user_input):
groceries = user_input.split(',')
my_dictionary={"Potato":12, "Onion":16, "Ginger":15, "Garlic":12, "Tomato":15}
total_price = 0
try:
for items in groceries:
total_price = total_price + my_dictionary[items]
print(total_price)
except KeyError:
for items in user_input:
if items not in my_dictionary:
print("Some groceries are not avaiable in the dictionary.")
break
get_grocery_price_1('Potato,Onion,Ginger')
# 42
get_grocery_price_1('Potato,Onion,Ginger,Beef')
# 'Some groceries are not avaiable in the dictionary.'
Here in the case when 'Beef' is not found in the groceries dictionary, a KeyError is raised, which is caught by your except block, printing your message.
2 Moving 'groceries not avialible' message into else statement
def get_groceries_price_2(user_input):
groceries = user_input.split(',')
my_dictionary={"Potato":12, "Onion":16, "Ginger":15, "Garlic":12, "Tomato":15}
total_price = 0
all_groceries_flag = True
for item in groceries:
if item in my_dictionary.keys():
total_price = total_price + my_dictionary[item]
else:
print("Some groceries are not avaiable in the dictionary.")
all_groceries_flag = False
break
if all_groceries_flag:
print(total_price)
get_grocery_price_2('Potato,Onion,Ginger')
# 42
get_grocery_price_2('Potato,Onion,Ginger,Beef')
# 'Some groceries are not avaiable in the dictionary.'
Here when a grocery is not a key of 'my_dictionary', a flag is changed,and the code breaks out of the for-loop adding up grocery prices.
So in summary, you need to use either if/else, or try/except logic to achieve your desired behaviour, but not both.
Also regarding your question of checking whether total_price is initialised, this can also be done using try/except or if/else.
Try except
try:
total_price
# rest of groceries logic
except NameError:
print('You do not have total_price variable')
Referencing an undefined variable will trigger a NameError, which you can catch in your except-block
If else
if 'total_price' in locals():
# rest of groceries logic
pass
else:
print('You do not have total_price variable')
Locally defined variables are stored in locals(), you can check if 'total_price' is defined in here.
Answered by oli5679 on January 27, 2021
You are defining if items in user_input, but not else part of it. In else part, you can manually raise exception:
for items in user_input:
if items in my_dictionary.keys():
total_price = total_price + my_dictionary[items]
else:
raise ValueError
print(total_price)
Answered by Homer on January 27, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP