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

Python while循环调用函数异常及空记录提示功能实现求助

问题修复与代码优化

核心问题解决

  • 选择'a'后无法退出录入流程:原代码仅在程序启动时获取一次用户选择,录入完成后循环不会重新询问选项,导致一直重复执行录入逻辑。把获取选择的代码移到循环内部,每次循环都重新获取用户输入即可解决。
  • 选择'b'时无记录无提示:当前代码仅处理了有记录的情况,为空列表添加else分支,打印“无可用记录”即可。

额外代码错误修正

  • display_results函数里,遍历运动员字典时,应该用当前循环的athlete对象取values(),而非列表athlete_results;同时字典的键"Time:"多了冒号,改为"Time"避免取值异常。

修复后的完整代码

menu = """Choose an option:
'a' = Input score
'b' = Display results
'c' = quit
>
"""

athlete_results = []

def input_scores():
    name = input("Name: ").strip().title()
    country = input("Country: ").strip().title()
    time = input("Time: ").strip()

    athlete_results.append({
        "Name": name,
        "Country": country,
        "Time": time  # 修正键名,去掉多余的冒号
    })

def display_results():
    for athlete in athlete_results:
        # 从当前运动员字典中解包值,注意顺序要和字典键的顺序一致
        name, country, time = athlete.values()
        print(f"{name}| {country}| {time}s")

while True:
    # 每次循环都重新获取用户选择
    choice = input(menu).strip().lower()
    if choice == 'a':
        input_scores()
    elif choice == 'b':
        if athlete_results:
            display_results()
        else:
            print('无可用记录')  # 添加空列表提示
    elif choice == 'c':
        break
    else:
        print("Invalid option!!!")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 21:01:53