S1Q3 · Double if Even, Else Square¶
⚡ Quick Reference
Function: double_if_even_else_square(n) -> int
Core idea: Check parity with n % 2 == 0, then return 2*n or n**2.
Key rules:
- Even (n % 2 == 0): return 2 * n
- Odd: return n ** 2
- Works for negative integers and zero (0 is even)
Problem Statement¶
Problem
Write a function double_if_even_else_square(n) that doubles n if it is even, or returns n squared if it is odd.
Examples:
double_if_even_else_square(8)
16
double_if_even_else_square(9)
81
Understanding the problem¶
n |
Even? | Operation | Result |
|---|---|---|---|
8 |
✅ | 2 × 8 |
16 |
9 |
✗ | 9² |
81 |
0 |
✅ | 2 × 0 |
0 |
-4 |
✅ | 2 × -4 |
-8 |
-3 |
✗ | (-3)² |
9 |
n % 2 works correctly for negative numbers in Python
In Python, % always returns a non-negative result when the divisor is positive. So -3 % 2 == 1 (odd) and -4 % 2 == 0 (even) -- both behave as expected. This differs from some other languages where % can return negative values.
Solution approaches¶
Key takeaways¶
Parity check: n % 2 == 0
The modulo operator % gives the remainder after division. n % 2 == 0 means no remainder when dividing by 2 -- the definition of even. Equivalently, n % 2 != 0 (or n % 2 == 1) means odd.
Ternary expression: a if condition else b
Python's inline conditional value_if_true if condition else value_if_false collapses a two-branch if/else into one line. Best used when both branches are short expressions, as here.
Exponentiation: n ** 2
** is Python's power operator. n ** 2 is equivalent to n * n but reads more naturally as "n squared". Both work; ** is preferred for clarity.