Quick Overview
n % 2 gives 0 for even and 1 for odd. Python keeps the sign of the divisor, so -3 % 2 is 1 here where C and JavaScript would return -1.
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!
A function with no return hands back None, so a forgotten one surfaces as a TypeError at the call site rather than at the line that actually caused it.
minutes * 60 returns an int when given an int, while / always produces a float regardless of the operands. Multiplication preserves the type; division does not.
base * height / 2 always yields a float in Python 3 because / never returns an int, even for whole numbers. // floors instead, which is almost never what an area wants.