Need help with test_boolean exercise

I’ve been sailing through the first few Python lessons, but I can’t seem to figure this practice question out. The part I’m having trouble with states:

Given the following code, which of the print() statements will NOT be executed?

test_string = “Code”
test_value = 50
test_boolean = False

if test_string == “Code”:
print(“String is equal!”)

if test_value < 100:
print(“Number is < 100!”)

if test_boolean:
print(“Boolean is True!”)

The explanation says: The print("Boolean is True!") will not be executed because test_boolean is set to False , so the if statement will NOT evaluate to True

Obviously the first two will be executed. But I thought the last one wouldn’t be executed because there is no operator like the first two (test_string == “Code” and test_value < 100. Why doesn’t the last example have to follow the same format (i.e. if test_boolean == True)?

This is the exercise I’m working on.

~~

in Python, the if statement evaluates the truthiness of the expression provided. If the expression evaluates to True, the associated block of code will execute. If it evaluates to False, the block will not execute.

So, when you have if test_boolean:, Python checks the truthiness of test_boolean. Since test_boolean is already a boolean value (False), Python directly evaluates it, and the if block will not execute if test_boolean is False.

Adding == True is redundant in this case, as it doesn’t change the behavior of the code; it’s equivalent to just using if test_boolean:. However, if you wanted to specifically check if test_boolean is True, you could use if test_boolean == True: or simply if test_boolean: for brevity.

1 Like

Got it, thank you very much for the explanation.

2 Likes