I'm currently learning Python and for my task it says to add the values of an array together. I tried:
no = ['1','2','3']
sum(no)
but had no luck in figuring out any way to find an answer. I'm also not supposed to use the sum
function.
Here's an example of the question if you need more info:
Define a function
sumStudentNo()
that will add the individual digits of your student number (excluding any letters) using an array and display the answer. Eg If your student number is's3456789'
, your program should display42
(ignore the's'
).Note you must NOT use the
sum
function.
Please help me.
If you are not allowed to use sum
(as in sum(int(n) for n in no)
), then you have to 1) convert every list element using int
and 2) sum them up.
s = 0
for n in no:
try:
s += int(n)
except ValueError:
pass
s = 0
no = "12p3s"
for i in no:
if i.isdigit():
s = s + int(i)
print s
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.