python - for循环序列中所有数字的总和
问题描述
我是 python 新手,我正在做有关循环的练习。我想知道如何获得 for 循环序列中所有数字的总和?
for num in (12, 1, 3, 33, -2, -5, 7, 0, 22, 4): # this is the sequence and it shouldn't be altered
if num == 0: # once it encounters 0 it should stop
print("Done")
break
continue
else:
print(sum(num)) # otherwise print the sum of all numbers
我以这种方式对其进行了排序,但这是一个不同的练习。
def process(numbers):
for num in numbers:
if num == 0:
break
else:
x = sum(numbers)
print(x)
return 'Done'
process(( 12, 4, 3, 33, -2, -5, 7, 0, 22, 4 ))
我希望看到第一种情况的解决方案,而不用定义带有序列参数的函数,就像在第一个代码块中一样。先感谢您。print(sum(num)) 不起作用,因为对象不可迭代。
解决方案
如果我们确定 0 存在,这可以以一种相当厚颜无耻的方式完成(代价是必须迭代列表两次并创建一个新列表):
sum(numbers[:numbers.index(0)])
但是正确的方法是使用您尝试过的显式循环,只需使用正确的逻辑:
def process(numbers):
s = 0
for num in numbers:
if num == 0:
break
s += num
print(s)
return 'Done'
推荐阅读
- botframework - 发送英雄或自适应卡片并在欢迎时获取用户输入
- python - Django-heroku 安装失败
- node.js - 在聊天消息中为同一事件获得两次通知
- google-cloud-platform - Google Cloud Compute Engine 未激活交换内存且无法通过 ssh 修复
- visual-studio-code - 如何在 VS Code 中使用断点调试 Ember 插件
- assembly - 汇编语言命令行
- python - Google Kick Start 2020 C 轮:稳定墙。总是 WA 但找不到问题
- jekyll - 如何在 Jekyll 中将字符串转换为日期?
- python - 使用 pip 安装后在 Anaconda 导航器上找不到包
- react-native - 无法解析模块 multer