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),".")
CodePudding user response:
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
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))
Expected output:
True
False
False
True
CodePudding user response:
So I assume you are given a number, for example "2345"
, and you are supposed to print "2, 4"
.
- Convert the number to string:
- Create empty list to append even digits and Iterate:
def evenDigits(num): num = str(num) evenNumbers = [] //empty list to store even numbers for digit in num: if digit % 2 == 0: //check if even digit evenNumbers.append(digit) return evenNumbers //returns list with even numbers num = input("Give me a number!") result = evenDigits(num) print(*result, sep = ", ") //will print all even digits on same line.
CodePudding user response:
You could create two separate functions for obtaining the digits and then checking if any digit is divisible by two.
from numbers import Number
from prettytable import PrettyTable
def get_digits(num: Number) -> list[int]:
return [int(d) for d in str(num) if d.isdigit()]
def contains_even(digits: list[int]) -> bool:
return any(x % 2 == 0 for x in digits)
def main() -> None:
t = PrettyTable(['x', 'digits', 'contains_even'])
t.align = "l"
for x in [11, -1230, -193.23, complex(5.4, 4.5), 23, 7.135, 0.354]:
d = get_digits(x)
t.add_row([x, d, contains_even(d)])
print(t)
if __name__ == '__main__':
main()
Output:
------------ ----------------- ---------------
| x | digits | contains_even |
------------ ----------------- ---------------
| 11 | [1, 1] | False |
| -1230 | [1, 2, 3, 0] | True |
| -193.23 | [1, 9, 3, 2, 3] | True |
| (5.4 4.5j) | [5, 4, 4, 5] | True |
| 23 | [2, 3] | True |
| 0.354 | [0, 3, 5, 4] | True |
------------ ----------------- ---------------