Tutorial for Debugging 2 Exercise

1. Open Mindtap and any Codespace

Open any Python exercise to access the github Codespace to run this code exercise.

2. Create new file and use the code

Right click at the left-sidebar and New File. Enter the name and copy paste the code:
1. Create file for Sales.py

  from datetime import datetime, timedelta

def get_ready(new_sales_file, used_sales_file, all_sales_file):
    try:
        new_sales = open(new_sales_file, 'r')
        used_sales = open(used_sales_file, 'r')
        all_sales = open(all_sales_file, 'w')
    except IOError:
        print("Error opening files.")
        return None, None, None, True

    return new_sales, used_sales, all_sales, False


def read_sales_data(file):
    line = file.readline()
    if line == '' or 'EOF' in line:
        return "EOF", 0
    try:
        salesperson, amount = line.strip().split(',')
        return salesperson, float(amount)
    except ValueError:
        print(f"Invalid line format: {line.strip()}")
        return None, 0


def detail_loop(new_sales, used_sales, all_sales):
    sales_data = {}

    # Process new sales data
    new_salesperson, new_amount = read_sales_data(new_sales)
    while new_salesperson != "EOF":
        sales_data[new_salesperson] = sales_data.get(new_salesperson, 0) + new_amount
        new_salesperson, new_amount = read_sales_data(new_sales)

    # Process used sales data
    used_salesperson, used_amount = read_sales_data(used_sales)
    while used_salesperson != "EOF":
        sales_data[used_salesperson] = sales_data.get(used_salesperson, 0) + used_amount
        used_salesperson, used_amount = read_sales_data(used_sales)

    # Write aggregated data to all_sales file
    for salesperson, amount in sorted(sales_data.items()):
        write_sales_data(all_sales, salesperson, amount)


def write_sales_data(file, salesperson, amount):
    file.write(f"{salesperson}, ${amount:.2f}\n")


def finish(new_sales, used_sales, all_sales):
    new_sales.close()
    used_sales.close()
    all_sales.close()


def main():
    new_sales_file = "NewSales.dat"
    used_sales_file = "UsedSales.dat"
    all_sales_file = "AllSales.dat"

    new_sales, used_sales, all_sales, error = get_ready(new_sales_file, used_sales_file, all_sales_file)

    if not error:
        kl_time = datetime.utcnow() + timedelta(hours=8)
        current_time = kl_time.strftime("%d-%m-%Y %H:%M:%S")
        all_sales.write("Here's the latest merge file between NewSales.dat and UsedSales.dat at " + current_time + ":\n\n")
        all_sales.write("Name | Sales\n")
        detail_loop(new_sales, used_sales, all_sales)
        print("Merging the both files UsedSales.dat and NewSales.dat, please check AllSales.dat for latest data.")

    finish(new_sales, used_sales, all_sales)


if __name__ == "__main__":
    main()   
    
2. Create file for NewSales.dat

Alice, 12000.50
Bob, 15000.75
Charlie, 18000.00
Emily, 20000.20
John Doe, 30000
Jane Smith, 25000
Raihan, 1200.00
Gross, 1600
Lil Pump, 2000
    
3. Create file for UsedSales.dat

Bob, 8000.00
Diane, 11000.50
Emily, 9500.75
Frank, 7000.25
Annaim, 100.00
Royy, 1500
Lil Pump, 99999
Big Pump, 100
    
4. Run the Sales.py. It will auto generate the file for AllSales.dat. The result should be like:
We have received your order. Now, please read and understand our Terms and Conditions before we continue.
Terms and Conditions

·        Accepted Payment: Only MYR bank transfers.

·        Payment Schedule: Up to 50% upfront payment before commencement of work. The final preview will be shown and the balance must be paid in full to receive the complete assignment.

·        Additional Fees: Extra charges apply for urgent tasks. We allow up to 3 revisions; extensive revisions thereafter will be charged.

·        Refund: Any request for a refund must be discussed with us first.

·        Confidentiality: We guarantee the confidentiality of all client data and assignment details unless required otherwise by legal obligations.

·        Timeline: Contact us at least two weeks before the desired delivery date. The initial three days are allocated for requirement discussions, pricing, and upfront payment.

·        Delivery Format: Assignments are delivered as digital documents via an online platform.

·        Revisions: Clients can provide comments for revisions. We offer up to three free revisions. Any further revisions start at RM20 each.

·        Change in Requirements: Alterations to initially agreed-upon requirements may result in the nullification of the agreement. Complete payment may be required if a total rewrite is necessary.

·        Termination: Contracts can be terminated if both parties agree. In such cases, only half of the deposit will be refunded.

·        Disclaimers: Our services are intended for reference or guidance purposes only and should not be submitted directly. We do not guarantee specific grades or outcomes.

By using Essay Scribe services, clients acknowledge and agree to these terms and conditions in their entirety.

You have acknowledged the Terms and Conditions, now please WhatsApp us for further discussion.