首页 > 解决方案 > python with sql table exceptional handling

问题描述

Premise: An SQL table has 4 columns: product, region, province, price. The region column can be either National or Provincial. If region is Provincial then province is filled (e.g. Ontario), otherwise it's blank. Each product has one national price, but may have zero or one provincial price. If a product has no provincial price, the national price is used. For example, "kale" may have a provincial price of $5.99 in Ontario and a national price of $4.50, with no other prices. If a user wanted to find the price of kale in Quebec they would get $4.50.

Challenge: Create a method, with a name and signature, that finds the price of a particular product in a particular province. Add the logic in pseudo-code to the body of the method. Be sure to include input parameters, a return statement, and any validation or exception handling that you deem necessary. You can represent the data as an array of objects.

this is the code which I have written which requires lot of modifications according to the person who has given me this assignment. Please modify/suggest as many changes as possible as I might have not considered few cases for exceptional handling

Assumption: Assuming the test input data is Valid leaving no data empty/NULL values at price or product or region. Also the code is starting here I could not format the code editor please help me immediately

#starting here

def getPriceOfProduct(data,product_name,province_name):   
#loop to run through the list/table data
for x in data:
   
    # Checking if the product exists
    if x[0].casefold() == product_name.casefold():
       
        # Checking if it is provincial / national
        if ((x[2].casefold() == province_name.casefold()) and x[1].casefold()=="provincial"):
            return x[3] #returning provincial price if product is found and the region matches with "provincial"
       # checking if region is national to return national price
        elif (x[2] == "" and x[1].casefold()=="national"):
            return x[3]
       #to convey if the product is not found in the list
else:
    return ("Product not found")                
       
input_data =[["Kale","Provincial","Ontario",5.99],["Kale","Provincial","Alberta",4.99],["Kale","National","",4.50],
             ["Celery","Provincial","Quebec",7.49],["Celery","National","",4.59],
             ["Lettuce","Provincial","Alberta",8.99],["Lettuce","National","",5.59],
             ["Parsley","National","",7.49],["Parsley","Provincial","Montreal",6.99],
             ["Broccoli","National","",9.49],["Broccoli","Provincial","Ottowa",11.99]]

result = getPriceOfProduct(input_data,"Broccoli","Quebec") #search here by changing product and province
print("Price of the product is: $",result)   

标签: pythonsqlpython-3.x

解决方案


推荐阅读