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

输入100/100未输出F反而重复提示,Python代码问题排查

Python分数计算程序问题解决

我正在学习Python,完成以下练习:

  • 接收用户输入的分数(X/Y)并返回结果
  • 若Y大于X,提示用户重新输入分数
  • 若X或Y不是整数,提示用户重新输入分数
  • 若X大于Y,提示用户重新输入分数
  • 若分数转换后结果≥99%,输出F
  • 若分数转换后结果≤1%,输出E

我的代码如下:

z = input("Fraction: ")
k = z.split("/")

while True:
    try:
        x = int(k[0])
        y = int(k[1])
        if y >= x:
           result = round((x / y) * 100)
        else:
           z = input("Fraction: ")
# if x and y are integer and y greater or equal to x, then divide, and round x and y

    except (ValueError, ZeroDivisionError):
        z = input("Fraction: ")

# if x and y are not integer or y is zero, prompt the user again

    else:
        break

# exit the loop if the condition is met and print (either F, E or the result of the division)

if result >= 99:
    print("F")
elif 0 <= result <= 1:
    print("E")
else:
    print(f"{result}%")

当输入100/100时,程序未按预期输出F,反而再次弹出输入提示,不清楚原因。


问题原因

核心问题是重新输入分数后没有更新分割后的数组。代码一开始只对第一次输入的内容做了分割,但后续在输入错误后重新获取输入时,没有重新分割新输入的内容,导致循环一直用最初的错误分割结果处理,触发异常后反复要求输入。

另外代码还有两处逻辑问题:

  1. 练习要求Y大于X时重新输入,但原代码里y >= x的分支会直接计算结果,和要求矛盾;
  2. 变量result可能在未初始化的情况下进入后续判断,会触发NameError。

修正后的代码

while True:
    z = input("Fraction: ")
    try:
        # 每次输入后立即分割并转换为整数
        x, y = map(int, z.split("/"))
        if y == 0:
            raise ZeroDivisionError
        # 严格按照练习要求:Y大于X或X大于Y都重新输入,仅X=Y时计算
        # 若练习描述笔误(实际允许X≤Y),可将判断改为`if x > y`
        if x != y:
            continue
        result = round((x / y) * 100)
        break
    except (ValueError, ZeroDivisionError):
        # 输入格式错误或除以0,重新输入
        continue

# 输出结果
if result >= 99:
    print("F")
elif result <= 1:
    print("E")
else:
    print(f"{result}%")

修改说明

  1. 将输入操作移到循环内部,每次循环都重新获取并处理新输入,彻底解决旧数据残留的问题;
  2. 用map(int, z.split("/"))简化分割和类型转换的代码;
  3. 显式判断Y为0的情况,逻辑更清晰;
  4. 严格按照练习要求设置输入判断(若练习描述有误,可自行调整判断条件);
  5. 确保result只有在合法输入时才会被赋值,避免未初始化的错误。

修改后输入100/100会正确计算出结果100,输出F。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 16:57:15