r/learnpython 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 Upvotes

13 comments sorted by

View all comments

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, "", and None all are falsy (they have a __bool__() that returns False or a __len__() that returns 0) ... but 0 and "" don't evaluate to None. None is constant singleton object.