You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python运费计算器代码问题:总运费统计与交互顺序调整

Fixing Fast Freight Shipping Company Calculator Issues

Let’s address the two core problems with your shipping calculator and provide a corrected implementation:

Problem 1: Incorrect Total Freight Calculation

The root issue is typically a missing or improperly managed total freight variable. You need to initialize the total outside the input loop and update it with each package’s cost after calculation.

Problem 2: Wrong Interaction Order

The flow must be adjusted to: calculate/display current package cost → update total → show accumulated total → ask if user wants to continue.

Corrected Code Example

def calculate_shipping(weight):
    # Replace with your actual rate logic
    if weight <= 2:
        return weight * 1.50
    elif weight <= 6:
        return weight * 3.00
    elif weight <= 10:
        return weight * 4.00
    else:
        return weight * 4.75

def main():
    total_freight = 0.0
    keep_going = True

    while keep_going:
        # Get package weight input
        weight = float(input("Enter package weight (lbs): "))
        
        # Calculate and display current package cost
        package_cost = calculate_shipping(weight)
        print(f"Package cost: ${package_cost:.2f}")
        
        # Update and show total freight
        total_freight += package_cost
        print(f"Total freight so far: ${total_freight:.2f}")
        
        # Ask to continue after displaying results
        response = input("Enter another package? (y/n): ").lower()
        if response != 'y':
            keep_going = False
    
    print(f"\nFinal total freight: ${total_freight:.2f}")

if __name__ == "__main__":
    main()

Key Fixes Breakdown

  • Total Freight Fix: total_freight is initialized once before the loop, and each package’s cost is added to it after calculation. This ensures all packages are included in the total.
  • Interaction Order Fix: The "continue" prompt is moved to after displaying the current package cost and accumulated total, aligning with the desired user flow.

Sample Expected Output

Enter package weight (lbs): 3
Package cost: $9.00
Total freight so far: $9.00
Enter another package? (y/n): y
Enter package weight (lbs): 7
Package cost: $28.00
Total freight so far: $37.00
Enter another package? (y/n): n

Final total freight: $37.00

内容的提问来源于stack exchange,提问作者kilo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 06:20:28