FOR loop logic question

Hi :slight_smile:

Gee, I could no longer log into the forum. Had to re-register…

I have resumed the Python beginner’s course and while playing around, I din’t quite get why the code above does not print Moron between 2 and Fool. Can anyone explain?

Seems like number == True only for 1. But this…

if bool(number) == True:

…should behave like you expect it to.

Hm, strange. He says in the videos that only the number 0, an empty “”, and the object None are False in Python, everything else is True.
So, I don’t see the difference between the numbers 0, 1, 2 or 285. The program understood me correctly in the case of 0 and 1…

The == operator compares the value of two objects. The Boolean True behaves like the value 1, and the Boolean False behaves like the value 0 . So 2 == True is like saying 2 == 1. The output of this code…

print(0 == False) # 0 == 0
print(1 == True) # 1 == 1
print(2 == True) # 2 == 1
print(2 == False) # 2 == 0

is

True
True
False
False

You should use the bool() function to get the Boolean value (True or False) of an object. The output of this code…

print(bool(0) == False)
print(bool(1) == True)
print(bool(2) == True)

is

True
True
True

Oh I see. So, Python did not think of my numbers as any old numbers, but as the foundation of digital, 0 and 1? Category mismatch…

Let your code simply read as follows:

for number in range(3):
print(number)
if number:
print(“Moron”)
print(“Fool”)
else:
print(“Bye”)

Do not introduce the bool ‘True’ in the nested ‘if’ an you will get the result you want.

You can try this out.