为什么测试 (100/100) 会导致意外的输出?

问题描述 投票:0回答:1

我正在尝试学习Python。在这种情况下,我进行了这个练习:

  • 我从用户那里获取一小部分(X/Y)并返回结果
  • 如果 Y 大于 X,我会提示用户提供另一个分数
  • 如果 X 或 X 不是整数,我会提示用户提供另一个分数
  • 如果 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
作为输出。

我不明白为什么。

python while-loop break
1个回答
0
投票

好吧,问题源于您对 K 变量的放置。当您最初将输入分配给 K 时,如果出于某种原因第一个输入抛出零除错误或值错误,则程序将无法按预期工作,因为您从不重新评估输入,因此只需将 k 变量移动到您的try 子句应该可以解决这个问题:

z = input("Fraction: ")
while True:
    try:
        k = z.split("/")
        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}%")
© www.soinside.com 2019 - 2024. All rights reserved.