Matt Matt - 5 months ago 21
Python Question

How to split a number in python and add them

I'm working on a lucky name numbers game, and I am able to get the number from the name by running it through a custom-made function, but I cannot seem to add them together.

My code so far:

num = 0

def main():
name = input('Please enter your name: ')
for letter in name:
if letter == 'a' or letter == 'j' or letter == 's':
num = num + 1
if letter == 'b' or letter == 'k' or letter == 't':
num = num + 2
if letter == 'c' or letter == 'l' or letter == 'u':
num = num + 3
if letter == 'd' or letter == 'm' or letter == 'v':
num = num + 4
if letter == 'e' or letter == 'n' or letter == 'w':
num = num + 5
if letter == 'f' or letter == 'o' or letter == 'x':
num = num + 6
if letter == 'g' or letter == 'p' or letter == 'y':
num = num + 7
if letter == 'h' or letter == 'q' or letter == 'z':
num = num + 8
if letter == 'i' or letter == 'r':
num = num + 9
getDigitSum()

def getDigitSum(num):
sum = 0
while num > 0:
num, remainder = divmod(num, 10)
sum += remainder
return sum

main()

Answer

Several obvious errors to this one:

  1. You aren't saving num after each for-loop run through. Since you called getDigitSum(num) with no arguments, there should be an error. Even if it did work (aka you changed the getDigitSum() to getDigitSum(num), it will still fail to work because num is not preserved after each run. TL:DR; change the line getDigitSum() in your main to num = getDigitSum(num).

  2. You aren't outputting anything in this code. the sum is not being printed after the program finishes. So, after you change the line getDigitSum() you should also include print(sum) after the for loop, inside main().

So, your code would look like this:

num = 0

def main():
    name = input('Please enter your name: ')
    for letter in name:
        if letter == 'a' or letter == 'j' or letter == 's':
            num = num + 1
        if letter == 'b' or letter == 'k' or letter == 't':
            num = num + 2
        if letter == 'c' or letter == 'l' or letter == 'u':
            num = num + 3
        if letter == 'd' or letter == 'm' or letter == 'v':
            num = num + 4
        if letter == 'e' or letter == 'n' or letter == 'w':
            num = num + 5
        if letter == 'f' or letter == 'o' or letter == 'x':
            num = num + 6
        if letter == 'g' or letter == 'p' or letter == 'y':
            num = num + 7
        if letter == 'h' or letter == 'q' or letter == 'z':
            num = num + 8
        if letter == 'i' or letter == 'r':
            num = num + 9
        num = getDigitSum(num)
    print(num)

def getDigitSum(num):
    sum = 0
    while num > 0:
        num, remainder = divmod(num, 10)
        sum += remainder
    return sum

main()

Please read up on StackOverflow's Asking Guidelines before asking a question, too.