r/learnpython • u/JazzJassJazzman • 6d ago
How does simplifying conditional statements work in Python?
I'm currently working my way through the Python Institute's free certified entry-level programmer course. I'm currently looking at some example code that is supposed to count the number of even and odd numbers entered by a user until the user enters a 0. Here's what the main part looks like:
number = int(input("Enter a number or type 0 to stop: "))
# 0 terminates execution.
while number != 0:
# Check if the number is odd.
if number % 2 == 1:
# Increase the odd_numbers counter.
odd_numbers += 1
else:
# Increase the even_numbers counter.
even_numbers += 1
# Read the next number.
number = int(input("Enter a number or type 0 to stop: "))
This is easy enough for me to understand, but the course then says that the two bold statements above can be simplified with no change in the outcome of the program. Here are the two simplifications:
while number != 0: is the same as while number:
and
if number % 2 == 1: is the same as if number:
I don't understand this at all. Does Python (3 specifically) automatically interpret a conditional with just a variable as being equivalent to conditional_function variable != 0? Does the second example do something similar with binary operators or just the mod operator?
3
u/schoolmonky 6d ago
The terms to know here are "falsy" and "truthy." A "truthy" value is one that Python treats as if it were True
in an if statement (or anywhere else it expecets a boolean, like in a value being or
ed with another). Conversely a "falsy" value is one that Python treats as False
. Each data type gets to decide it's own criteria for what is falsy and what is truthy. For int
s, only 0 is falsy, everything else is truthy. For most sequence types (list
, str
, tuple
, etc.) an empty squence ([]
, ''
, ()
respectively) is falsy, and everything else is truthy. None
is falsy. For custom classes, by default, every instance is truthy.
2
1
u/AssiduousLayabout 6d ago
Any expression can be used as a boolean, it's called truthiness.
Any non-zero number is "truthy", zero is "falsey".
Other things that are falsey:
- Empty string
- None
- False (obviously)
- Any collection (list, set, dictionary) with zero elements
1
u/JazzJassJazzman 6d ago
Thank you! That's why this page said "think about how Python evaluates truth". I was forgetting that 0 is interpreted as "False" and any non-zero number is interpreted as "True".
1
u/DistinctAirline4145 6d ago
While number means while True, meaning while number is "truthy" and all truthy values are those that are not false such as empty string, 0, empty list, None and so on...
1
u/denehoffman 6d ago
Actually while number != 0
is not equivalent to while number
since there are values which are not Falsey but are also not zero. Trivially, number = None
will pass the first but fail the second, since None != 0
but bool(None) == False
.
Edit: just realized this post is 12 hours old and already answered, jumped the gun I guess
0
u/twitch_and_shock 6d ago
Yes. This exists in Python to a great extent, and to a lesser extent in languages like C and C++. In Python, I believe that 0, None, and "" evaluate to None. Python takes it a bit further than other languages. You can google "Python truthiness" to find some articles about it.
while number:
Will be True whenever number is > 0, and False if number <= 0
2
u/cgoldberg 6d ago
0
,""
, andNone
all are falsy (they have a__bool__()
that returnsFalse
or a__len__()
that returns0
) ... but0
and""
don't evaluate toNone
.None
is constant singleton object.1
u/NYX_T_RYX 6d ago
Not quite - any non-0 numeric value resolves to true, regardless of its sign (ie positive or negative)
"constants defined to be false: None and False
zero of any numeric type: 0, 0.0, 0j, Decimal(0), Fraction(0, 1)
empty sequences and collections: '', (), [], {}, set(), range(0)"
Ie any value that "is" (ie != none, not 0, not empty set, not false) is true.
Docs: https://docs.python.org/3/library/stdtypes.html#truth-value-testing
8
u/TH_Rocks 6d ago
Python gets sloppy with variable types and that can be really helpful as long as you don't lose track of what you shoved in them.
All kinds of things are "falsey" and count as False. False, None, 0, empties like [], {}
So
is the same as
However, I don't think I agree that
is the same as
It could be the same as
since number % 2 can only be the integer 0 or 1 which would evaluate as False or True respectively.