Home > Net >  while loop won't works right in python
while loop won't works right in python

Time:12-13

I wrote this code for summing up digits of a number which is bigger than 10 until the result only have one digit and when I try to compile it, it won't even give me an error until I stop it. I want to know what's the problem.

number = input()
#sumed_up_digits = result
result = 0

while len(number) != 1:
    for i in number:
        int_i = int(i)
        result = result   int_i

     number = str(result)

print(result)

CodePudding user response:

Try the following code:

   s=input()
   n=len(s)
   result=0
   for i in range(n-1):
      result=result int(s[i])
   print(result)

This for loop runs from 0th to (n-2)th index of the given string, hence the last digit will not be added to the result. Like for 1245, it will add 1,2 and 4 to result, but not 5.

CodePudding user response:

result is cumulative and include previous sums. try:

number = input()
#sumed_up_digits = sum
sum = 0

while len(number) != 1:
    result = 0
    for i in number:
        int_i = int(i)
        result = result   int_i
    sum = sum   result
    number = str(result)

print(sum)

CodePudding user response:

You can do it like this:

number = input()

if len(number) <= 1:
    print(0)

while len(number) > 1:
    number = str(sum(int(i) for i in number))

print(int(number))

Of course, you would need to check that the initial input number is made of digits...

CodePudding user response:

the problem is number isn't being shortened so the condition for the loop to stop is never reached.

number = input()

result = 0
while len(number) != 1:
    # set digit to last number
    digit = int(number) % 10
    result  = digit
    number = number[:-1]

print(result)
  • Related