我正在尝试学习Python。在这种情况下,我进行了这个练习:
我的代码如下:
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
作为输出。
我不明白为什么。
好吧,问题源于您对 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}%")