+ 1

(Python): How to Convert String to Integer using While Loop and then find the sum?

So, I was able to make a program that adds the sum of a string of numbers in a for loop. However, I can’t figure out how to do it for a while loop. Here’s what I have for a for loop. num_string = “2514” sum= 0 for dig in num_string: sum+=int(dig) print(sum) Here’s my while loop that I’m struggling on. while num_string >= 0: sum += int(dig) print(sum) I honestly have the worst Professor in the world, so I’m trying to figure this all out on my own. I’ve tried googling it and looking at his “examples,” but I either can’t find anything or it doesn’t make sense. I’m terrible at Python, so explaining in layman’s terms would be helpful.

13th Oct 2019, 8:21 PM
Blair Green
Blair Green - avatar
2 Respuestas
+ 3
there is a solution to do it without loops in case you don't know num = "1234" num = [int(i) for i in list(num)] total = sum(num) print(total)
14th Oct 2019, 1:05 AM
Shen Bapiro
Shen Bapiro - avatar
+ 1
1. It's not recommended to use built-in functions (e.g. sum) as variable names as it can mess up with your code. 2. In this case, a "for" loop is better than a "while" loop, but if you must use it try this: num_string = "2514" total = 0 i = 0 while i<len(num_string): total += int(num_string[i]) i += 1 print(total) # 12
13th Oct 2019, 8:36 PM
Diego
Diego - avatar