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)