0

I am taking a Python course, the following is an example code snippet; I understand it:

# A program that reads a sequence of numbers
# and counts how many numbers are even and how many are odd.
# The program terminates when zero is entered.

odd_numbers = 0
even_numbers = 0

# Read the first number.
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: "))

# Print results.
print("Odd numbers count:", odd_numbers)
print("Even numbers count:", even_numbers)

Then this portion appears in the lesson:

Try to recall how Python interprets the truth of a condition, and note that these two forms are equivalent:

while number != 0: and while number:.

I subbed in the while number: in the code above and the code functions correctly.

I don't understand WHY while number: means while number !=0

Can anyone explain this to me? Thank you!

4 Answers4

0

It has to do with truthy and falsy values, better explained in this article.

Basically, when you use a while or if operator, you are evaluating that value in a boolean context, 0 is considered a falsy value, so it evaluates to False.

sgck
  • 141
  • 1
  • 9
  • kinda important to add that _any_ other integer evaluates to `True` – Matiiss Jan 01 '22 at 17:25
  • Ok, I think I understand what you are saying. Basically, since Zero evaluates as 'false' I don't need to specify that '!=0' for the condition to be 'true' because any other value (other than Zero) for the variable 'number' will be evaluated as a 'true' condition and will trigger the loop. Is this correct? – OinkerOinker Jan 01 '22 at 17:34
0

in Python False and 0 are sort of the same thing, same for True and 1. as @Matiis mentioned in the comment above.

while number

or any thing looks like this, means while this variable neither equals False, Zero nor None, the same applies for if

if number
Feras Alfrih
  • 492
  • 3
  • 11
0

As another user has already said, the reason that this has the same result is because 0 is interpreted as False in the context of the while loop, while anything other than 0 is interpreted as True.

Therefore, while number and while number != 0 will both be True while the number is anything other than 0.

Paul Burkart
  • 132
  • 1
  • 6
0

while expect a boolean and bool(0) returns False

bool(0)
False

bool(10)
True

and

0 != 0
False

10 != 0
True

That the reason why

while number != 0

is the same that

while number
Malo
  • 1,233
  • 1
  • 8
  • 25