为什么100分的测试会产生意外输出?
我正在学习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 个回答
2
好的,问题出在你对K变量的放置上。你在最开始给K赋值的时候,如果因为某种原因,第一个输入出现了零除错误或者值错误,程序就不会按预期工作,因为你没有重新评估输入。因此,把你的K变量放到try语句里,或者更准确地说,放到while循环里,应该能解决这个问题:
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: ")
continue
# 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}%")
另外,建议你在提问时要更清楚,确保提供你所有的输入。最好的方法是重新运行你的程序,记录下所有的输入,包括在这种情况下的空输入。
补充说明:在y小于x的情况下添加了一个继续的语句,这样就会要求再输入一次,因此结果就不会被定义。