简体   繁体   中英

Python 3.4 : Trying to get this module to sum the sale totals in this 2d array. Not working

def sales_per_zip(sales):
    sales_sum = 0
    i = 1
    print(sales[1][0])
    zipcode = input("Enter the Zip Code here:")
    if zipcode == sales[1][0]:
        while i <= 6:
            sales_sum =+ sales[1][i]
            i =+ 1
            print(i)

    print(sales_sum)

sales = [
["Zip Code", "Mocha", "Latte", "Regular", "Decaf", "Caramel"],
[48093,180,100,200,180,150],
[48088,270,330,160,150,250],
[48026,240,310,450,100,320],
[48066,200,230,350,110,360],
]
opt = ""

print("What would you like to do?")
print("Z = Get Total Sales by Zip Code.")
print("C = Get Total Sales by Coffee Type.")
print("G = Get Grand Total of all Coffee Sales.")
print("HZ = Get Highest Sales by Zip Code.")
print("HC = Get Highest Sales by Coffee Type.")
opt = str(input("Enter your option here:"))

if opt == "z" or opt == "Z":
    sales_per_zip(sales)
#elif opt == "c" or opt == "C":
#
#elif opt == "g" or opt == "G":
#
#elif opt == "hz" or opt == "HZ":
#
#elif opt == "hc" or opt == "HC":

This is what i have so far. The first def is not summing the sales correctly. The output is just a 0 I can't seem to see why. I'm currently in my first python/programming class. I have this running in raptor but transferring it to python is becoming quite the task...

You have some incorrect operators =+ instead of += . Also, you need to parse the input zipcode as a int. Lastly, the while loop should have < instead of <= so you don't get an IndexError.

def sales_per_zip(sales):
    sales_sum = 0
    i = 1
    print(sales[1][0])
    zipcode = int(input("Enter the Zip Code here:"))
    if zipcode == sales[1][0]:
        while i < len(sales[1]):
            sales_sum += sales[1][i]
            i += 1
            print(i)

    print(sales_sum)

Additionaly, you could add another function to make sure you get a valid input zipcode.

def get_zipcode():
    try:
        zipcode = int(input("Enter the Zip Code here:"))
        return zipcode
    except:
        print("ERROR: zipcode must be an integer")
        return get_zipcode()

def sales_per_zip(sales):
    sales_sum = 0
    i = 1
    print(sales[1][0])
    zipcode = get_zipcode()
    if zipcode == sales[1][0]:
        while i < len(sales[1]):
            sales_sum += sales[1][i]
            i += 1
            print(i)

    print(sales_sum)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM