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

Python字典特定键输入无效时如何实现重试而非跳过?

修复分数输入脚本的重复验证问题

需求说明

  • 编写Python脚本,向用户请求5个分数输入,每个分数对应稀释度列表dil中的一项:1:16、1:32、1:64、1:128、1:256
  • 仅允许输入corr_input中的6种有效字符串:"+", "++-", "-", "+-", "-a", "A"
  • 输入"q"可立即退出并展示已录入的稀释度与分数

问题描述

当前脚本在用户输入无效值时,会直接跳过对应稀释度的录入,未将该稀释度加入scores字典;需要修改为针对当前稀释度重复请求输入,直到用户提供有效分数或输入"q"退出。

当前代码

dil = ["1:16", "1:32", "1:64", "1:128", "1:256"]
corr_input = ["+", "++-", "-", "+-", "-a", "A"]
scores = {}

for dil in dil:
    testscore = input("Enter score: ")
    try:
        if testscore in corr_input:
            scores[dil] = testscore
        elif testscore == "q":
            print("Done!")
            break
        else:
            print("Not a valid score!")
    except TypeError:
        print("Invalid input! Try again")
        break
print(scores)

当前运行结果

######### 
Enter score: +
Enter score: +
Enter score: v
Not a valid score!
Enter score: +
Enter score: +
{'1:16': '+', '1:32': '+', '1:128': '+', '1:256': '+'}

修复后的代码

dil_list = ["1:16", "1:32", "1:64", "1:128", "1:256"]
corr_input = ["+", "++-", "-", "+-", "-a", "A"]
scores = {}

for dil in dil_list:
    while True:
        testscore = input(f"输入{dil}对应的分数: ")
        if testscore in corr_input:
            scores[dil] = testscore
            break
        elif testscore == "q":
            print("已退出!")
            break
        else:
            print("无效分数!请重新输入。")
    if testscore == "q":
        break
print(scores)

代码说明

  1. 重命名原列表变量为dil_list,避免与循环中的单元素变量dil重名,提升代码可读性
  2. 针对每个稀释度,用while True循环持续请求输入,直到用户提供有效分数或输入"q"
  3. 输入提示明确标注当前对应的稀释度,让用户清晰知晓输入目标
  4. 输入"q"时,直接保留已录入数据并退出所有循环
  5. 移除不必要的try-except块,因为input()本身不会抛出TypeError

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 19:33:25