Learn how to use Python modulo arithmetic to determine if an integer is even or odd.
Learn how to convert minutes into seconds in Python using arithmetic multiplication and basic unit conversions.
Create a function is_even_or_odd(num) that takes an integer and returns "even" if the number is even, and "odd" if the number is odd.
Determining even/odd numbers is a classic algorithmic building block used in grid layouts, zebra striping table rows, and partitioning list elements.
Check if num % 2 == 0 using an if/else conditional:
def is_even_or_odd(num):
if num % 2 == 0:
return "even"
else:
return "odd"
# Alternative 1-liner using Python Ternary Expression
def is_even_or_odd_fast(num):
return "even" if num % 2 == 0 else "odd"
# Testing our function
print(is_even_or_odd(3)) # Output: "odd"
print(is_even_or_odd(14)) # Output: "even"
print(is_even_or_odd(0)) # Output: "even"
Python uses value_if_true if condition else value_if_false for inline 1-line conditional assignments.
0 % 2 == 0 is True). Ensure your logic correctly identifies 0 as even!Use ternary expressions for clean 1-line returns. Next, let's retrieve the first element of a list!