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.
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.
Boolean comparison operators (<, <=, >, >=, ==, !=) are the decision-making engine behind conditional control flow in Python.
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
In Python, booleans are capitalized: True and False (unlike JavaScript's lowercase true and false).
if num <= 0: return True else: return False is redundant! The expression num <= 0 ALREADY evaluates directly to a boolean True or False. Return the expression directly!= is for variable assignment. Double == or <= is for equality and comparison.Return boolean expressions directly. Next, let's solve the Farm Problem animal legs challenge!
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.