-1

How can I show an error message "please input a valid number" if I enter a string which is not a float? Because when I input a string I will get an error:

ValueError: could not convert string to float:

My code:

 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)
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Bryan
  • 1

3 Answers3

0

you should do error handling.

example:

while True:
  try:
    your_variable = float(input("Input string"))
    break
  except:
    print("please input a valid number")
N0ll_Boy
  • 500
  • 3
  • 6
0
try:
    u = float(input('Enter the initial velocity in m/s :'))
except Exception as e:
    print(e)

Output

could not convert string to float: 'bad string'
Sudipto
  • 299
  • 2
  • 11
0

The approach in Python can be "better to ask forgiveness than permission", so catch the error and loop around. This is a common action for all your numeric inputs, so it naturally implies an auxiliary function:

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

and then your main code would look like:

 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)

Your prompts for v are wrong - based on the formula, it should be final velocity, not acceleration.

Joffan
  • 1,485
  • 1
  • 13
  • 18