Back to Freecodecamp

Step 21

curriculum/challenges/english/blocks/learn-how-to-work-with-numbers-and-strings-by-implementing-the-luhn-algorithm/65687b48f2201ab32e06c37c.md

latest2.3 KB
Original Source

--description--

Currently, your script throws a TypeError because you are trying to add a string to an integer. You can fix this by converting the digit variable to an integer before adding it to sum_of_odd_digits, using the built-in int function:

python
my_string = '123'
my_int = int(my_string)

Convert the digit variable to an integer before adding it to sum_of_odd_digits. Then, move the print call to the end of the verify_card_number function to print the value of sum_of_odd_digits.

--hints--

You should have sum_of_odd_digits += int(digit) within the for loop.

js
({
    test: () => {
        const transformedCode = code.replace(/\r/g, "");
        const verify_card_number = __helpers.python.getDef("\n" + transformedCode, "verify_card_number");
        const { function_body } = verify_card_number;

        assert.match(function_body, /sum_of_odd_digits\s*\+=\s*int\(\s*digit\s*\)/);
    }
})

You should have print(sum_of_odd_digits) at the end of the verify_card_number function.

js
({
    test: () => {
        const transformedCode = code.replace(/\r/g, "");
        const verify_card_number = __helpers.python.getDef("\n" + transformedCode, "verify_card_number");
        const { function_body } = verify_card_number;

        assert.match(function_body, /print\(\s*sum_of_odd_digits\s*\)/);
    }
})

You should not have print(digit) anymore.

js
({
    test: () => {
        const transformedCode = code.replace(/\r/g, "");
        const verify_card_number = __helpers.python.getDef("\n" + transformedCode, "verify_card_number");
        const { function_body } = verify_card_number;

        const no_comments = __helpers.python.removeComments(function_body);

        assert.notMatch(no_comments, /print\(\s*digit\s*\)/);
    }
})

--seed--

--seed-contents--

py
def verify_card_number(card_number):
    sum_of_odd_digits = 0
    card_number_reversed = card_number[::-1]
    odd_digits = card_number_reversed[::2]

--fcc-editable-region--
    for digit in odd_digits:
        print(digit)
        sum_of_odd_digits += digit
        
--fcc-editable-region--
def main():
    card_number = '4111-1111-4555-1142'
    card_translation = str.maketrans({'-': '', ' ': ''})
    translated_card_number = card_number.translate(card_translation)

    verify_card_number(translated_card_number)

main()