如何使其在输入字符串而不是浮点时打印出“请输入有效数字”

2024-09-24 04:30:01 发布

您现在位置:Python中文网/ 问答频道 /正文

如果输入的字符串不是浮点数,如何显示错误消息“请输入有效数字”?因为当我输入一个字符串时,我会得到一个错误:

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)

Tags: the字符串in消息inputif错误float
3条回答
try:
    u = float(input('Enter the initial velocity in m/s :'))
except Exception as e:
    print(e)

输出

could not convert string to float: 'bad string'

Python中的方法可以是“请求原谅比请求许可更好”,因此捕捉错误并循环。这是所有数字输入的常见操作,因此它自然意味着一个辅助功能:

def float_input(prompt):
    while True:
        try:
            return float(input(prompt))
        except ValueError:
            print('Number required, please re-enter')

然后您的主代码将如下所示:

 if unknown == 'S':
  if units.lower() == 'si':  
    u = float_input("Enter the initial velocity in m/s :")
    v = float_input("Enter the acceleration in m/s : ")
  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 taken in s : ")
    
  S = 0.5 * (u + v) * t
  print("S is " , S)

您对v的提示是错误的-根据公式,它应该是最终速度,而不是加速度

您应该执行错误处理

例如:

while True:
  try:
    your_variable = float(input("Input string"))
    break
  except:
    print("please input a valid number")

相关问题 更多 >