我已经通过了所有测试,但我只是好奇“1.5/3”或“2.5/5”等输入如何重新提示? 下面是代码:
def main():
percentage = -1
while percentage == -1:
fraction = input('Fraction: ')
percentage = convert(fraction)
return_val = gauge(percentage)
print(return_val)
def convert(fraction):
try:
#if / not in fraction, not enough values to unpack so ValueError
numerator, denominator = fraction.split('/')
numerator = int(numerator)
denominator = int(denominator)
if numerator <= denominator and denominator != 0:
return round((numerator/denominator)*100)
else:
raise ValueError
except ValueError:
return -1
def gauge(percentage):
if percentage <= 1:
return 'E'
elif percentage >= 99:
return 'F'
else:
return f'{percentage}%'
if __name__ == "__main__":
main()
问题链接:问题
问题要求指定分子和分母都是整数。如果您尝试将浮点值类型转换为整数,Python 将抛出异常。为了涵盖分子和分母的十进制值的情况,我们需要将它们转换为浮点数,然后进行除法。最终值将是一个浮点数,无论如何,整数都会出现这种情况,并且您必须将其转换回整数。
请看下面的代码:
def main():
f = get_fraction_value('Fraction: ')
if f >= 99:
print('F')
elif f <= 1:
print('E')
else:
print(f'{f}%')
def get_fraction_value(prompt):
while True:
try:
n,d = input(prompt).split('/')
result = 100*float(n)/float(d)
if result>100:
raise ValueError
else:
return int(result)
except (ValueError, ZeroDivisionError):
pass
main()