# Calculating total Price of groceries with execptions in Python

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:

1. Handle the exception when the given key is not present in the dictionary.
2. Handle the exception when the summation variable is not initialized.

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?

Stack Overflow Asked by ShemTheUltimate on January 27, 2021

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

## Related Questions

### Unable to parse the links of different cases from next pages using requests

2  Asked on November 29, 2021 by robots-txt

### Discord.py error: TypeError: __new__() got an unexpected keyword argument ‘deny_new’

5  Asked on November 29, 2021 by daniel-tam

### How to handle cookies across domains in development

3  Asked on November 29, 2021 by user3379926

### How to get the accurate time position of a live streaming in avplayer

3  Asked on November 29, 2021 by raychen

### Copy each cell in a range to multi-cell range

2  Asked on November 29, 2021 by preston-richardson

### processDebugResources FAILED after changing icon launcher

2  Asked on November 29, 2021 by roz333

### Material UI + React Form Hook + multiple checkboxes + default selected

4  Asked on November 29, 2021 by manos

### regex – how to capture pattern without different pattern before it?

4  Asked on November 29, 2021

### Image slider – How to check if element is partially out of parent div Horizontally

1  Asked on November 29, 2021

### In Openshift, how can I create a new build with an environment variable that’s value is a secret using the CLI?

1  Asked on November 29, 2021 by kennybartman

### How to start app module in multi-module application unit test

0  Asked on November 29, 2021 by mohamed-hamdan

### (IONIC – Angular) How can i show in html cards, only certain objects from a JSON that match certain criteria?

1  Asked on November 29, 2021 by agus-dllano

### How to make dynamic custom textarea with jquery?

3  Asked on November 29, 2021 by david-noya

### private static field Java

3  Asked on November 29, 2021

### unordered_map excess calls to hash function

4  Asked on November 29, 2021 by amir-kirsh

### How to turn array of objects in unique array?

3  Asked on November 29, 2021

### Setting the width of an article in Javascript doesn’t update

2  Asked on November 29, 2021 by user11914177

### Parsing Strings and Integers in JavaScript

2  Asked on November 29, 2021

### cant load static file in django

1  Asked on November 29, 2021

### How to add field description to mongodb collection

1  Asked on November 29, 2021