Learn How to Work with Numbers and Strings by Implementing the Luhn Algorithm

Hi everyone! So I’m at the end of the implementation of the Luhn Algorithm and I have now created this function:

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

    for digit in odd_digits:
        sum_of_odd_digits += int(digit)

    sum_of_even_digits = 0
    even_digits = card_number_reversed[1::2]
    for digit in even_digits:
        number = int(digit) * 2
        if number >= 10:
            number = (number // 10) + (number % 10)
        sum_of_even_digits += number
    total = sum_of_odd_digits + sum_of_even_digits
    print(total)
    return total % 10 == 0

And now I am here, trying to do this:
“Adjust the verify_card_number call such that if it returns True , print 'VALID!' to the console. Otherwise, print 'INVALID!' .”

Now I understand that the correct answer is this, because after some tryes I ended up with the right answer but I haven’t really understood why:

if verify_card_number(translated_card_number):
        print("VALID!")
    else: 
        print("INVALID!")

I mean, if I have to print Valid if the verify_card_number returns True, shouldn’t it be something like this?

if verify_card_number(translated_card_number) == True:
        print("VALID!")
    else: 
        print("INVALID!")

Thanks in advance.

First of all, pay attention to the indentation: if and else must have the same indentation.

About the condition of the if statement:
Values can be truthy or falsy, meaning that can evaluate either to True or False.
In general, empty lists, empty dictionaries, empty strings and so on evaluates to False, as well as the number 0. While non-zero numbers and non-empty objects evaluate to True.

If you write the expression verify_card_number(translated_card_number) == True and that function call returns True, the expression True == True is evaluated (the value is True of course) and it will work fine, but you don’t need to compare it since Python will evaluate the truthiness/falseness of the condition value.

1 Like

IF condiftion works as below

IF True :
execute

The function itself is returning either True or False based on the return expression condition (return total % 10 == 0 ) . So if the return expression is True , the “IF” condition will be True else False.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.