如果输入的字符串不是浮点数,如何显示错误消息“请输入有效数字”?因为当我输入一个字符串时,我会得到一个错误:
ValueError: could not convert string to float:
我的代码:
if unknown == 'S':
if units in ('si', 'Si'):
u = float(input("Enter the initial velocity in m/s :"))
v = float(input("Enter the acceleration in m/s : "))
t = float(input("Enter seconds : "))
else:
u = float(input("Enter the initial velocity in yards/s :"))
v = float(input("Enter the acceleration in yards/s : "))
t = float(input("Enter the time take in s : "))
S = 0.5 * (u + v) * t
print("S is " , S)
输出
Python中的方法可以是“请求原谅比请求许可更好”,因此捕捉错误并循环。这是所有数字输入的常见操作,因此它自然意味着一个辅助功能:
然后您的主代码将如下所示:
您对
v
的提示是错误的-根据公式,它应该是最终速度,而不是加速度您应该执行错误处理
例如:
相关问题 更多 >
编程相关推荐