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

Python字典添加输入设默认值及嘉年华票务跟踪代码问题修复

修复方案

核心问题说明

  • buy_slinkies 函数使用普通除法实现,不符合「向下取整兑换整数个弹簧玩具」的需求规范,改用整数除法更稳妥
  • 游戏过程的循环仅采集了玩家姓名和票数变动数据,没有将变动同步更新到 players 字典中,最终统计时读取的始终是初始票数
  • 输入的票数变动为字符串格式,未转换为整数无法直接参与数值计算
  • 字典新增输入项+设置默认值的需求可以通过字典的get()方法实现:读取键值时如果键不存在,直接返回指定的默认值,再将更新后的值写回字典即可同时完成新项添加和旧项更新。

修复后完整代码

def buy_slinkies(tickets):
    # 用整数除法直接实现向下取整,返回整数结果
    return tickets // 3

# Write the rest of your program here
players = {}

print("Who's here at the carnival today?")
friends = input('Name: ')
while friends:
    starting = int(input('Starting tickets: '))
    players[friends] = starting
    slinkies = buy_slinkies(starting)
    print(f"{friends}'s here, starting with {slinkies} slinkies worth of tickets!")
    friends = input('Name: ')
  
print('Let the games begin!')

current_player = input('Who played? ')
while current_player:
    # 转换票数变动为整数
    ticket_change = int(input('Tickets won/lost: '))
    # get方法第二个参数为默认值:玩家不存在时默认初始票数为0,更新后写回字典
    players[current_player] = players.get(current_player, 0) + ticket_change
    current_player = input('Who played? ')

print("End of the day! Let's see how everyone did!")

for human, total_tickets in players.items():
    final_slinkies = buy_slinkies(total_tickets)
    print(f"{human} can buy {final_slinkies} slinkies.")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 12:27:04