Check sum in list comprehension
Is it possible to also check the sum of the digits in the list in the same comprehension a开发者_StackOverflownd make another except if the sum exceeds 50?
k = input("input digits separated by spaces:")
try:
[int(i) for i in k.split()]
except ValueError:
print("input only digits")
The main thing is not to structure it with two except blocks, but to keep it as simple as possible make sure that the sum of the list is not more than 50.
k = input("Input integers separated by spaces:")
try:
the_list = [int(i) for i in k.split()]
if sum(the_list) > 50:
raise ValueError("The user's numbers' summation is too large.")
except ValueError:
print("Input only integers separated by spaces with sum not greater than 50.")
assert sum([int(i) for i in k.split()]) <= 50
and add an except
AssertionError
would do the trick:
k = input("input digits separated by spaces: ")
try:
assert sum([int(i) for i in k.split()]) <= 50
except ValueError:
print "input only digits"
except AssertionError:
print "Sum of digits is grater than 50"
Though I must say that I find this a rather poor design...
精彩评论