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

Python新手求助:实现循环购票到用户选否,统计总票数及总金额

Python门票售卖程序实现方案

修正后完整可运行代码

# 初始化累计变量,存储总购票数和总消费金额
total_tickets = 0
total_cost = 0

while True:
    # 单次购票逻辑
    tickets = int(input("How many tickets would you like? "))
    current_cost = tickets * 5
    # 累计数据更新
    total_tickets += tickets
    total_cost += current_cost

    print(f"You ordered {tickets} tickets and your total is {current_cost} Dollars")

    # 询问是否继续购买
    continue_purchase = input("Would you like to continue? Y/N \n").strip()
    if continue_purchase == "N":
        # 输入N则跳出循环输出汇总
        break
    elif continue_purchase != "Y":
        print("Invalid input, please enter Y or N")

# 输出汇总结果
print("\n===== 历史交易汇总 =====")
print(f"累计购票总数:{total_tickets} 张")
print(f"累计总消费金额:{total_cost} 美元")

核心改动说明

  • 直接在程序入口初始化两个累加变量,每次完成单次购票后同步更新累计值,不需要额外用列表存储也能实现跨循环的数据统计。如果你需要保留每次的购买记录后续做其他分析,也可以用列表存储每次的购票数,汇总时调用sum()方法求和即可:
    # 列表存储方案示例
    ticket_history = []
    # 循环内购票后执行
    ticket_history.append(tickets)
    # 汇总时计算
    total_tickets = sum(ticket_history)
    total_cost = total_tickets * 5
    
  • 调整了循环结构,把所有购票逻辑都移入循环中,避免重复写冗余代码,同时修正了原代码中输入Y后不会重新询问是否继续的死循环问题
  • 补充了输入N跳出循环后的汇总输出逻辑,新增了简单的非法输入兼容处理

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 19:54:02