+ 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.
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)
+ 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