If Statements
if
statements are used for truth value testing. In this lesson, you learned that you don’t need to explicitly compare a value to True
or False
, you can simply add it to the if
statement:
Bad
if value == True:
print 'truthy'
if value2 == None:
print None
Good
if value:
print 'truthy'
To compare a value to False
, use the not
operator:
if not value1:
print 'falsy'
Explicitly check for None
:
if value2 is None:
print None
00:00
The next idiom I’d like to discuss is the if
statement, so we have a few expressions here that we can use to show and illustrate the example here. First, we’ll discuss the poor way of going about it.
00:11
We have an expression that evaluates to True
or False
and then we run that against the if
statement. Now, in Python, this is a redundant step.
00:20
We can simply check to see if the value itself is True
or False
. So as you can see here—let me just comment this out. As you can see here, they both evaluate the same way. This is a little bit cleaner, a little bit easier to write.
00:33
The next is to illustrate how the False
statement would work. That’s simply by putting a not
in front of whatever value you want to evaluate to True
so that it prints 'falsy'
.
00:48 And as you can see, that also works.
00:51
The next expression is the evaluation of None
, which is slightly different and we’ll get into that in another talk, but to check against None
, you simply use the is
statement.
Become a Member to join the conversation.