我正在练习两周后我将要参加考试的问题,每当我尝试尝试这个问题时,我都会迷失方向。我已经尝试将args放入int(args)但得到" ValueError:对于带有基数10的int()的无效文字:"。
我不允许使用任何for循环或任何使这项任务变得简单的函数。
import sys
args = sys.argv[1]
total = 0
i = 0
while i < len(args):
total = total + args[i]
print total
答案 0 :(得分:1)
答案 1 :(得分:0)
如果你这样做:
import sys
print " ".join(sys.argv[1:]) # skip the programs name which is given as argv[0]
它将打印所有你的论点,分开一个“”。
示例:强>
python
yourScriptName.py
one
two
three
four
将打印
one two three four
要总结“数字”命令行参数,可以使用:
import sys
def floatOrZero(tmp):
f = 0.0
try:
f = float(tmp) # make a float. # Lots of things are floats: 1.3e9
except:
f = 0.0 # this happens for non-floats
return f
# sum all convertable parameters and print result
# using a list comprehension to convert args (strings) into
# floats or 0.0 if not convertable
print "Sum of numeric entries: " , sum([floatOrZero(num) for num in sys.argv])