0

here's my code for credit.py. I feel as though it should be working as it validates my specific visa number, but won't validate the numbers that were provided by Check50 for the C problem. I feel as if the error is in the while loop where the checksum is being generated as I am printing the checksum on each iteration as a form of debugging (as I haven't quite got to grips with python debugging yet), as the checksum sequence given for the AMEX card 378282246310005 is 5,-4,-4,-13,-12,-11,-5,-4,-2,-1,7,8,16,16,19. Obviously there should be no negative numbers in there. Have I missed something in the use of the ternary operator?

Here is the stack exchange thread I used to find out about python's ternary operator: https://stackoverflow.com/questions/394809/does-python-have-a-ternary-conditional-operator

...
# now must manipulate the number to verify if it is a valic CC number
# generates a checksum according to Luhn’s algorithm
# if mod of checksum == 0 then CC is valid
while (num > 0):
    # mod by 10 to get last digit
    digit = num % 10

    if multiply:
        # uses a form of ternary operator
        checksum += (digit < 5) if (digit * 2) else ((digit*2) - 9)
    else:
        checksum += digit

    print(checksum)
    num //= 10
    multiply = not multiply

...

0

Apparently, upon reading the Stack Exchange thread in more depth, the order of arguments to the ternary operator in Python is different to most other C like languages, and that it is actually written like this:

<condition if true> if <argument being checked> else <condition if false>

This essentially swaps round the first and second arguments, which is confusing from the point of view of logic and having come from C, but actually reads a little clearer in English.

For clarity, ternary operators in C are written like this:

<argument being checked> ? <condition if true> : <condition if false>

These links might also be helpful:

https://docs.python.org/3/faq/programming.html#is-there-an-equivalent-of-c-s-ternary-operator

https://docs.python.org/3/reference/expressions.html#conditional-expressions

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .