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
def has_even_digit(num): while num != 0: result = 0 i = 1 digit = num % 10 if digit % 2 == 0: # even digit found return True else: result += digit * i i *= 10 num = num // 10 return False print(has_even_digit(45)) print(has_even_digit(13)) print(has_even_digit(1579315)) print(has_even_digit(780278452))
True False False True
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
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)