Python Forum

Full Version: Can somebody check what is wrong with my code?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
The purpose of the code is to add the digits of the factorial product such as 5! = 120 and the output is 1 + 2 = 3.
import math
num = 10
fac = math.factorial(num)
list = []
n = 0
sum = 0
while fac > 0:
     digit = (fac // 10 ** (n-1)) % 10
     n += 1
     list.append(digit)
     for i in list:
         sum+=i
         break
print(sum)
Looks to me like you want to create a list of digits by repeatedly dividing over fac. I see a few problems with this.

1. Your while loop test is while fac > 0, but fac is never changed. Even if n is greater than the number of digits, the while test is still successful.

2. Your sum method is not correct. You're appending to a list in the while loop, then before exiting the while loop you're trying to add up all the digits in the list. You need to either add the digits as you encounter them, or you need to add up all the digits in the list after you're done appending to the list.

3. What do you intend the break on line 13 to do? As written, the line 11 for loop will only ever run one iteration.
EDITED for clarification

Never use built-ins like list and sum as variable names unless you like to live dangerously and recklessly.

Examples of surprises you may encounter:

>>> list('abc')
['a', 'b', 'c']
>>> sum([1, 2, 3])
6
>>> list = []
>>> list('abc')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable
>>> sum = 0
>>> sum([1, 2, 3])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
It is ok to use list and sum, just not as variable names. I'm sure I'm not the only one to do a double take after reading "Never use built-ins like list and sum unless you like to live dangerously and recklessly."

Your code for getting the digits is very confusing. I think you had an idea and started to code before it was fleshed out. It think you were trying to do this:
    digitsum = 0
    while fact > 0:
        digitsum += fact % 10
        fact //= 10
But you got lost somewhere and forgot to change fact each time through the loop, resulting in a loop that never ends. And because you forgot to change fact you thought you had to divide by increasing powers of 10. I still have no idea why you are using a list to store the digits.
(Sep-15-2020, 05:06 PM)deanhystad Wrote: [ -> ]It is ok to use list and sum, just not as variable names. I'm sure I'm not the only one to do a double take after reading "Never use built-ins like list and sum unless you like to live dangerously and recklessly."

You are right & my bad. I edited my post to better express what I wanted to say.