Python运费计算器代码问题:总运费统计与交互顺序调整
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_freightis 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): nFinal total freight: $37.00
内容的提问来源于stack exchange,提问作者kilo

