-3
import sys

n = len(sys.argv)

average = 0.0
value_1 = float(sys.argv[1])
value_2 = float(sys.argv[2])
value_3 = float(sys.argv[3])

if value_1 or value_2 or value_3 == str:
    print("Your input is invalid!")
else:
    total = value_1 + value_2 + value_3
    average = total / 3
    print("Average:%.2f" % average)


I tried using if else statement where if input is str it will display an error message however it is not working.

  • 1
    Your code doesn't really make sense - `float` would already raise an error if the input is inconvertible. – AKX Sep 09 '22 at 14:13
  • If you want check the type of a value, it's `isinstance(x, y)`, not `x == y`. – chepner Sep 09 '22 at 14:14
  • 1
    @chepner The duplicate is not applicable here, since OP's `if` statement doesn't make sense. – AKX Sep 09 '22 at 14:14
  • It's applicable; it's just not *complete*. There are multiple issues here; we can add additional duplicates to cover the type-checking issue. – chepner Sep 09 '22 at 14:14
  • (Even if the proper solution is to do away with multiple conditions, the OP is still under the mistaken assumption that `x or y or z == a` is the way to check if `x == a` or `y== a` or `z == a`.) – chepner Sep 09 '22 at 14:16

1 Answers1

2
  • float would raise an error if it can't convert the input, so there's no point in checking things in an if statement afterwards.
  • You'd use ifinstance(x, str) to check if x is a string.
    • Furthermore, to check for multiple conditions, you would need to repeat the entire "subcondition".
  • You're not using n for anything.

A version of your code that would have more correct error handling (catches both conversion errors and not having enough inputs) is

import sys

try:
    value_1 = float(sys.argv[1])
    value_2 = float(sys.argv[2])
    value_3 = float(sys.argv[3])
except (ValueError, IndexError):
    print("Your input is invalid!")
else:
    total = value_1 + value_2 + value_3
    average = total / 3
    print("Average:%.2f" % average)

A version that tries to convert any variable number of arguments:

import sys

try:
    values = [float(arg) for arg in sys.argv[1:]]
except ValueError:
    print("Your input is invalid!")
else:
    if not values:
        print("No input, can't compute average")
    else:
        total = sum(values)
        average = total / len(values)
        print("Average:%.2f" % average)
AKX
  • 152,115
  • 15
  • 115
  • 172