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.
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.ifinstance(x, str)
to check if x
is a string.
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.