数字列表按顺序打印和打印所有数字,直到打印数字的总和超过100.我需要使用while循环重写函数 I cannot use for, break or return.
如果数字之和小于或等于100,则打印列表中的所有数字 . 下面包括我对问题的尝试(这是错误的......),以及我想要实现的输出 . 我想知道您如何尝试解决问题的想法或您对我的代码逻辑的建议 . 非常感谢提前:D
def print_hundred(nums):
""" Hundy club """
total = 0
index = 0
while index < nums[len(nums)]:
print(nums)
total += nums[index]
else:
if total > 100:
print(total)
print_hundred([1, 2, 3])
print_hundred([100, -3, 4, 7])
print_hundred([101, -3, 4, 7])
test1 (Because the sum of those numbers are still less than 100)
1
2
3
test2 (100 - 3 + 4 = 101, so the printing stops when it exceeds 100)
100
-3
4
test3 (Already exceeds 100)
101
2 回答
我有这个代码也有效:
输出:
这可能不是最优雅的方式,但是考虑到你的限制,这是最好的 -
输出 -