Check if Number is Less Than or Equal to Zero
Quick Overview
Python chains comparisons, so `0 <= n <= 10` is one expression and evaluates `n` exactly once. Writing it with `and` gives the same answer but evaluates the middle term twice.
Deep Dive
1. The Challenge: Boolean Comparison
Create a function less_than_or_equal_to_zero(num) that takes a number as its only argument and returns True if it's less than or equal to zero, otherwise return False.
2. Why It Matters
Boolean comparison operators (<, <=, >, >=, ==, !=) are the decision-making engine behind conditional control flow in Python.
3. The Python Solution
Use the <= comparison operator, which returns a boolean True or False:
def less_than_or_equal_to_zero(num):
return num <= 0
# Testing our function
print(less_than_or_equal_to_zero(5)) # Output: False
print(less_than_or_equal_to_zero(0)) # Output: True
print(less_than_or_equal_to_zero(-2)) # Output: True
4. Python Boolean Principles
In Python, booleans are capitalized: True and False (unlike JavaScript's lowercase true and false).
5. Common Mistakes
- Unnecessary If/Else Wrap: Writing
if num <= 0: return True else: return Falseis redundant! The expressionnum <= 0ALREADY evaluates directly to a booleanTrueorFalse. Return the expression directly! - Confusing = with ==: Single
=is for variable assignment. Double==or<=is for equality and comparison.
6. Next Steps
Return boolean expressions directly. Next, let's solve the Farm Problem animal legs challenge!
Next Up in Python Beginner Practice & Core Problem Solving
Return the Sum of Two Numbers
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.
Convert Minutes into Seconds
`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.
Calculate the Area of a Triangle
`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.