【发布时间】:2014-01-19 03:03:31
【问题描述】:
我正在阅读 Guttag 博士的“Python 计算和编程简介”一书。我正在为第 3 章做手指练习。我卡住了。这是第 3.2 节,第 25 页。练习是:让 s 是一个字符串,其中包含用逗号分隔的十进制数字序列,例如,s = '1.23,2.4,3.123'。编写一个程序,打印 s 中的数字之和。
前面的例子是:
total = 0
for c in '123456789':
total += int(c)
print total.
我已经尝试过,但不断收到各种错误。这是我最近的尝试。
total = 0
s = '1.23,2.4,3.123'
print s
float(s)
for c in s:
total += c
print c
print total
print 'The total should be ', 1.23+2.4+3.123
我收到ValueError: invalid literal for float(): 1.23,2.4,3.123.
【问题讨论】:
-
conert 字符串使用 >>> a = "1.23" float(a) >>1.23 浮动。如果在您的情况下有多个字符串,则将它们拆分并使用 float 函数。
-
一个提示:查看sn-p
total += c。c是一个字符串,因此您尝试将字符串添加到整数total。