是否也可以用相同的推导方式检查列表中的数字总和,并进行另一个计算,除非总和超过 50?
k = input("input digits separated by spaces:")
try:
[int(i) for i in k.split()]
except ValueError:
print("input only digits")
最主要的是不要用两个 except block 来构造它,而是要使其尽可能简单,并确保列表的总和不超过 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.")
关于python - 检查列表理解中的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7282538/