数字列表nums并按顺序打印nums中的所有数字,直到打印的数字之和超过100。我需要使用while循环重写函数,我不能使用for、break或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
我有一个代码,它也可以工作:
输出:
这可能不是最优雅的方式,但考虑到你的限制,这是最好的-
输出-
相关问题 更多 >
编程相关推荐