What can I write for an if condition?

Question

What can I write for an if condition?

Answer

Any expression that results in True or False is a viable condition for an if statement in Python. There are endless possibilities of things you could combine to make such an expression, but some we’ve learned so far are:

  • Expressions using comparators like ==, >, etc.
  • Expressions using not, and, and or
  • But there are other ways to express truth values! For example, we can return a value from a function and check that value returned, or even just return True or return False and then write if function_name(). Another possibility is using 0 for False and 1 for True!
7 Likes

2 posts were split to a new topic: How to Use return?

what is - return true - what does it mean ? can you give examples please :frowning:

5 Likes

I don’t know the answer to that

1 Like

He means the return to a function. A function is written like this:
def boolFunction():
return True

This function would “return” True, so when you write the if clause you could write: if boolFunction():. This would evaluate True (because the function we are calling just returns the value True. If I were to replace the True value for a string an error would be generated.

3 Likes

If you are asking what to write in the underline to return true,
to my understanding anything can be in used to replaced in the underline that will give you a True
4 > 1 will return True
4 == 1 will return False
3+9 > 9+1 will return True
etc

2 Likes

To my knowledge, any number that isn’t 0 or 1 will also return true, Correct me if I’m wrong, but I believe it is because it is viewed as a matter-of-fact statement of sorts. For example, the number 36 will equal true if used in an if statement, because it exists and is equal to itself by definition. But to my knowledge this doesn’t work outside of an if statement. The if statement forces 36 to become a boolean. So this if statement here will return true:
if (40 and 35):
print(True)

A peculiar thing is that outside of the if statement print(36 and 26) returns 26, while print(36 or 26) returns 36. I’m hoping someone can enlighten me as to why this is?

1 Like

0 would be the only integer that evaluates to False. If you need to test the truthiness of an object then the built-in function bool() can be used.

Your second chunk of code is an example of boolean short-circuits in Python. The following provides and few examples of how this works if you’re curious-

1 Like

Any function learned in previous section that would output a true statement
e.g.
not 1 > 1 ===> True
cat" != “rat”
3**2 == 81 * 0.5 (aka 81^(1/2) = squared root of said number)

1 Like