0

I'm building a program to calculate the shipping costs for a parcel. I would like to give the user the opportunity to input the weight of the parcel using the input() function.

I would like the program to return "Invalid input" if anything but an integer or float is inputted. I've tried using the following code:

weight = input("How heavy is the package you want to ship? ")
while type(weight) == float or int:
  if weight <= 2:
    price_per_pound = 1.50
  elif weight <= 6:
    price_per_pound = 3.00
  else:
    price_per_pound = 4.00
  break

else:
  print("Invalid input")

However, I get an error saying '<=' not supported between instances of 'str' and 'int'. I know that in Python 3 input() always returns a string, so I've also tried this:

weight = float(input("How heavy is the package you want to ship? "))

But if the user inputs a character, it returns the error "could not convert string to float".

I'm pretty new to programming, any help would be appreciated. Thanks!

  • `== float or int` doesn't do what you think. `float or int` is `float`. – Peter Wood Aug 23 '21 at 20:08
  • try this https://stackoverflow.com/a/32252634/10666066 – AcaNg Aug 23 '21 at 20:08
  • `type(weight)` is always going to be `string`. You can check for integer with `.isnumeric`, but float either requires a regex or a `try`/`except` block around `float(weight)`. – Tim Roberts Aug 23 '21 at 20:10
  • Please also see https://stackoverflow.com/questions/20002503/why-does-a-x-or-y-or-z-always-evaluate-to-true . @PeterWood the order of operations isn't what you imply, either. – Karl Knechtel Aug 23 '21 at 20:12

0 Answers0