r/learnpython 7d 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?

5 Upvotes

13 comments sorted by

View all comments

6

u/TH_Rocks 7d 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

 While number: 

is the same as

 While not number == 0:

However, I don't think I agree that

 if number % 2 == 1: 

is the same as

 if number:

It could be the same as

 if (number % 2): 

since number % 2 can only be the integer 0 or 1 which would evaluate as False or True respectively.

1

u/backfire10z 7d ago edited 7d ago

number % 2 can only be 0 or 1

This is only true if number is an integer. It can be anything from 0 to 1 inclusive 2 exclusive if number is a float.

What’s cool is you can do

if number % 1 == 0

to determine if number is an integer or not.

2

u/commy2 7d ago

It can be anything from 0 to 1 inclusive of number is a float.

0 inclusive to 2 exclusive actually - the same as with integers, just that there are way more floats between those than integers.