first, or it may be because the script logic says it makes more sense to check for a negative condition.
You can negate the result of a condition check by using the logical not operator (see Hour 5):
Click here to view code image
>>> a = 1
>>> if not(a == 1): print("The 'a' variable is not equal to 1")
>>> if not(a == 2): print("The 'a' variable is not equal to 2")
The 'a' variable is not equal to 2
>>>
The not operator reverses the normal result from the equality comparison, so the opposite action
occurs from what would have happened without the not operator.
By the Way: Negating Conditions
You may have noticed that you can negate a condition result by either using the not
operand or by using the opposite numeric operand (such as!= instead of ==). Both
methods produce the same result in your Python script.
Summary
This hour covers the basics of using the if structured command. The if statement allows you to set
up one or more condition checks on the data you use in your Python script. This comes in handy when
you need to program any type of logical comparisons in your Python scripts. The if statement by
itself allows you to execute one or more statements based on the result of a comparison test. You can
add the else statement to provide an alternative group of statements to execute if the comparison
fails.
You can expand the comparisons by using one or more elif statements in the if statement. You can
just continue stringing elif statements together to continue comparing additional values.
In the next hour, we’ll take a look at some more advanced control statements you can use to make your
scripts more dynamic. We’ll discuss the Python statements that allow you to loop through sections of
your code multiple times!
Q&A
Q. Does Python support the select and case statements that are often found in other
programming languages?
A. No, you have to use the elif statement to string together multiple if condition checks.
Q. Is there a limit on how many statements I can place in an if or else code block?
A. No, you can add as many statements as you need to control inside the if or else code
blocks.
Q. Is there a limit on how many elif statements I can place in an if statement?
A. No, you can nest as many elif statements together as you need to check in your code. However,
you may want to be careful, as the more elif statements the longer it will take for Python to
evaluate the code values.