[英]Python Exceptions difficulty
我正试图尽快完成一个实验,但我遇到了困难,提示是:
计步器将步行 2,000 步视为步行 1 英里。 编写一个 steps_to_miles() function,它将步数作为参数并返回步行的英里数。 steps_to_miles() function 抛出 ValueError object 消息“异常:输入负步数。” 当步数为负时。 完成从用户读取步数的 main() 程序,调用 steps_to_miles() function,并输出 steps_to_miles() 的返回值 function。使用 try-except 块捕获 steps_to_miles 抛出的任何 ValueError object () function 和 output 异常消息。
Output 每个小数点后两位的浮点数,实现方式如下: print('{:.2f}'.format(your_value))
我已经研究了一段时间了,我的代码是:
def steps_to_miles():
steps = int(input())
if steps < 0:
raise ValueError
return steps
if __name__ == '__main__':
try:
steps = steps_to_miles()
miles_walked = float(steps / 2000)
print('{:.2f}'.format(miles_walked))
except ValueError:
print('Exception: Negative step count entered.')
(抱歉出现格式错误...)代码运行但只给我 10 分中的 4 分,因为 Zybooks 指出“test_passed function missing”和“Test stepsToMiles(-3850), should throw an exception”。 我缺少什么或如何解决? 或者还有另一种编写代码的方法吗?
def steps_to_miles(steps):
if steps < 0:
raise ValueError
return float(steps / 2000)
if __name__ == '__main__':
steps = int(input())
try:
miles_walked = steps_to_miles(steps)
except ValueError:
print('Exception: Negative step count entered.')
print('{:.2f}'.format(miles_walked))
input
移到main
。 下一个错误:steps 是局部变量,在全局命名空间和 function main
中没有使用对于自动作业评分器,我们无法为您提供很多帮助,您可能应该询问您的老师或助教。 这里有几个指针:
steps_to_miles
不采用任何 arguments,根据分配它应该采用单个 integer 参数。ValueError
没有附加消息。steps_to_miles
应该将它的论点除以 2000,但它没有这样做。 相反,您在 function 之外除以 2000。except
块中打印特定字符串,而不是打印异常的实际消息。您可能需要将您的错误消息设为一个变量,关于您的 zyBooks 给您这个错误:“Test stepsToMiles(-3850)。
我会在你的 function 中尝试这个: raise ValueError('Exception: Negative step count entered.')
我也会在你最后的“except”语句中写下这个。
except ValueError as err:
print(err)
这应该有效:
def steps_to_miles(num_steps):
if num_steps < 0:
raise ValueError("Exception: Negative step count entered.")
return num_steps / 2000
if __name__ == '__main__':
num_steps = int(input())
try:
num_miles = steps_to_miles(num_steps)
print('{:.2f}'.format(num_miles))
except ValueError as e:
print(e)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.