[SOLVED] No idea on how to create a function that determines if a number has an even digit within

Table of Contents


I am learning to create functions. The whole program basically prints only the even digits of a number, but I need to create a function that, in case the number has no even digits, will print that it doesn’t have any, but I have no idea on how to make the condition.
Thanks in advance.

So far this is the code without the function I need:

def imprimirPares (num):
    while num != 0:
        resultado = 0
        i = 1
        digito = num % 10
        if digito % 2 == 0:
            resultado += digito * i
            i *= 10
        num // 10
    return resultado

def ingresarEyS (num):
    print ("Nuevo numero con los valores pares de la cifra: ")
    num = ()
    print ("El nuevo numero es ",imprimirPares(num),".")


Using your already existing function this is fairly easy. One error you have made is that you do not assign the result of num // 10 to num though.

def has_even_digit(num):
    while num != 0:
        result = 0
        i = 1
        digit = num % 10
        if digit % 2 == 0:
            # even digit found
            return True
            result += digit * i
            i *= 10
            num = num // 10
    return False


Expected output:



As @Sash Sinha pointed out this solution only works for positive integers. Adjusting it for all integers is easy though using num = abs(num) before starting the while loop.

If you need this to work for float or complex a solution using str will be easier to implement and cleaner as demonstrated in @Sash Sinha’s answer below.

Answered By – Mushroomator

Answer Checked By – Robin (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *