Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
141 views
in Technique[技术] by (71.8m points)

python - Calculate total amount deliveries

For you to solve my problem I think you have to run it on your own. My problem is in this line print(Customer_Name, "has spent", Customers[Customer_Name]['TotalAmount'], "in total")

Output

For you to understand better. For example here, It says Michael has spent 60.0 in total when it should be Michael has spent 20.0 in total

 import datetime
 import uuid  # GET A RANDOM ID FOR THE CUSTOMER
 from csv import DictWriter
 from datetime import date  # GET CURRENT DATE AND TOMORROW DATE
 import os


def openFile():  # STARTS HERE
    try:
        os.startfile('data_entered.csv')

    except Exception as e:
        print(str(e))
        # OPEN FILE WHEN USER(EMPLOYEE) WANTS TO


def closeFile():
    try:
        os.system('TASKKILL /F /IM notepad.exe')

    except Exception as e:
        print(str(e))  # ENDS HERE


file = open('CustomerNames.txt', 'a')
file1 = open('Orders_Per_Users.txt', 'a')
file2 = open('data_entered.csv', 'a')

ORDERS_FROM_EMPLOYEE = 0
x = -1
length = 0
Total_Amount = 0.0
Customer_List = []
Address_List = []
My_List = []
today = datetime.date.today()
Today_Key = date.toordinal(date.today())
Today_Date = date.today()
Tomorrow_Date = datetime.date.today() + datetime.timedelta(days=1)
Customers = {}
Dates = {}

print("Welcome to our coffee shop!")
print("Login")

# EMPLOYEE LOGIN PROCESS STARTS
UserLogin = {"Employee1": "coffeeshop1", "Employee2": "coffeeshop2", "Employee3": "coffeeshop3"}
username = password = ''
while True:
    username = input("Username: ")
    password = input("Password: ")

    if (username in UserLogin) and (UserLogin[username] == password):
        print("Login Successful")
        break
    else:
        print("Invalid Login. Try again")
# EMPLOYEE LOGIN PROCESS ENDS

# PROCESS AFTER ORDER PLACEMENT STARTS
print("Current Date is: {}".format(Today_Date))
process1 = True
process2 = True
while process1:
    while process2:
        x += 1

        Customer_Name = input("Customer's Name:")
        Customer_Address = input("Customer's Address:")

        if Customer_Name in Customer_List and Customer_Address in Address_List:
            First_Index = Customer_List.index(Customer_Name)
            Second_Index = Address_List.index(Customer_Address)
            if Customer_Name == Customer_List[First_Index]:
                Customer_List.pop(First_Index)
                x -= 1

        Address_List.append(Customer_Address)
        Customer_List.append(Customer_Name)

        if Today_Key not in Dates:
            Dates[Today_Key] = {}
            if Customer_Name not in Dates[Today_Key]:
                Dates[Today_Key][Customer_Name] = 1
            else:
                Dates[Today_Key][Customer_Name] += 1

        if Customer_Name in Customers:
            Customers[Customer_Name]['Orders'] += 1
            Customers[Customer_Name]['TotalAmount'] = Total_Amount
        else:
            Customers[Customer_Name] = {}
            Customers[Customer_Name]['Name'] = Customer_Name
            Customers[Customer_Name]['Address'] = Customer_Address
            Customers[Customer_Name]['ID'] = uuid.uuid1()
            Customers[Customer_Name]['Orders'] = 1
            Customers[Customer_Name]['TotalAmount'] = 0

        Order_Price = float(input("Total amount of order:"))
        ORDERS_FROM_EMPLOYEE += 1

        print(Customer_Name, "has ordered {} time(s)".format(Customers[Customer_Name]['Orders']))

        Total_Amount = Order_Price + Total_Amount

        if Tomorrow_Date == Today_Date:  # WHEN THIS IS TRUE, IT MEANS THAT THE DATE CHANGED
            print("Total amount of orders today is:{} ".format(Total_Amount))  # NUMBER OF ORDERS IN ONE SPECIFIC DAY
        answer1 = input("Send another order? (Y/N)").lower()

        if Customers[Customer_Name]['Orders'] == 1:
            print("This is the first time", Customer_Name, "orders")
            Customers[Customer_Name]['TotalAmount'] = Order_Price
        else:  # TOTAL AMOUNT OF ALL ORDERS DELIVERED
            print(Customer_Name, "has spent", Customers[Customer_Name]['TotalAmount'], "in total")

        process2 = answer1 == "y"

    LengthCustomersList = len(Customer_List)
    length += 1

    if int(length) == int(LengthCustomersList):
        process1 = False

file1.write(username + " has placed {} orders today".format(ORDERS_FROM_EMPLOYEE))

for i in Customer_List:
    file.write(i + '
')

csv_writer = DictWriter(open('data_entered.csv', 'a'),
                        fieldnames=['Customer Name', 'Customer Address', 'Customer ID', 'Total Orders',
                                    'Total Amount'])

csv_writer.writeheader()

for customer_name in Customers.keys():
    csv_writer.writerows(
        [{'Customer Name': Customers[customer_name]['Name'],
          'Customer Address': Customers[customer_name]['Address'],
          'Customer ID': Customers[customer_name]['ID'],
          'Total Orders': Customers[customer_name]['Orders'],
          'Total Amount': Customers[customer_name]['TotalAmount']}])

openFile()

file.close()
file1.close()
file2.close()

I have tried adding a Customers[Customer_Name]['Order_Price'] but it did not work


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your issue is with the Total_Amount variable. Its value is kept from the last iteration and assigned to the next customer. You need to retrieve it from your Customers dictionary and then update the value in the dictionary after.

if Customer_Name in Customers:
    Customers[Customer_Name]['Orders'] += 1
    # Customers[Customer_Name]['TotalAmount'] = Total_Amount  # This is where the error was
else:
    Customers[Customer_Name] = {}
    Customers[Customer_Name]['Name'] = Customer_Name
    Customers[Customer_Name]['Address'] = Customer_Address
    Customers[Customer_Name]['ID'] = uuid.uuid1()
    Customers[Customer_Name]['Orders'] = 1
    Customers[Customer_Name]['TotalAmount'] = 0

Total_Amount = Customers[Customer_Name]['TotalAmount']  # retrieve value here

Order_Price = float(input("Total amount of order:"))
ORDERS_FROM_EMPLOYEE += 1

print(Customer_Name, "has ordered {} time(s)".format(Customers[Customer_Name]['Orders']))

Total_Amount = Order_Price + Total_Amount
Customers[Customer_Name]['TotalAmount'] = Total_Amount  # update value here

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...