if Statements In Python
A SIMPLE EXAMPLE
What we want to do? We have a list of cars
that contains the name of cars in lowercase letter. We want to print the names of all in title case expect from ‘byd’, which should be all in upper case To achieve this we will combine a for
loop with if-else
statements
How it works? The loop in this example first checks if
the current value of car
is ‘byd’ .If it is, the value is printed in uppercase. else
(If the value of car
is anything other than ‘byd’) it’s printed in title case.
1. CONDITIONAL TESTS
At the heart of every if
statement is an expression that can be evaluated as True or False and is called a conditional test
If a conditional test evaluates to True, Python executes the code following the
if
statement.If the conditional test evaluates to False, Python ignores the code following the
if
statement. If we have providedelse
statement, then that code will be executed
1.1. Checking for Equality
Single equal sign =
is used to assign a value to a variable, whereas double equal sign ==
is to check
for equality — this equality operator returns True if the values on the left and right side of the operator match, and False if they don’t match.
Ignoring Case When Checking for Equality
Testing for equality is case sensitive in Python as we seen above
This test would return True no matter how the value ‘BYD’ is formatted because the test is now case insensitive.
1.2. Checking for Inequality
When you want to determine whether two values are not equal, we use the conditional operator !=
— the exclamation point represents not
1.3. Numerical Comparisons
We can compare the numerals the same way as we did the strings.
Using various mathematical operators
We can use following comparison operators :
>
greater than
<
less than
>=
greater than or equal to
<=
less than or equal to
1.4. Checking Multiple Conditions
We can use and
or or
to check to check the True or False status of multiple conditions:
and
— when you might need two conditions to be True to take an actionor
— when you might need either of two conditions to be True to take an action
Using and
condition
and
conditionTo check whether two conditions are True simultaneously, we use the keyword and
to combine the two conditional tests.
If both conditional tests pass, the overall expression evaluates to True
If either or both conditions fail, the expression evaluates to False.
To improve readability of our code, we can use parentheses ( )
around the individual tests, but they are not required
Using or
condition
or
conditionThe or
condition returns True when either or both of the individual tests pass. It will return False only when both individual tests fail.
1.5. Checking Whether a Value is in
a List
in
a ListSometimes, it’s important to check whether a list contains a certain value before taking an action. To find out whether a particular value is already in a list, we use the keyword in
.
1.6. Checking Whether a Value is not in
a List
not in
a ListOther times, we would like to know if a value does not appear in a list. In this case, we can use the keyword not in
this situation.
1.7. Boolean Expressions
A Boolean expression is just another name for a conditional test whose value is either True or False. We have studied earlier in part 1 about Boolean data type and the same logic applies here.
2. Types of if STATEMENTS
There are few types of if
statements, and your choice of which to use depends on the number of conditions you need to test.
2.1 Simple if
Statements
if
StatementsSome basic examples of if
statements have been discussed, the general syntax of if
statement is as follows:
Logic → If the conditional test evaluates True, Python executes the code following the if statement. If the test evaluates to False, Python ignores the code following the if statement
NOTE: All indented lines after an if
statement will be executed if the test passes, and ignored if the test fails
2.2. if-else
Statements
if-else
StatementsAn if- else
block is similar to a simple if
statement, but the else
statement allows you to execute some code when the conditional test under if
fails
2.3. The if-elif-else Chain
Often, you’ll need to test more than two possible situations, for these situations you can use Python’s
if- elif- else
syntax.
Remember that Python executes only one block in an if- elif- else chain
depending on which condition is True. That is, it runs each conditional test in order until one passes, when a test passes, the code following that test is executed and Python skips the rest of the tests For example, the price for museum varies with age:
For kids under 4 age, price is $0
For kids and teen above 4 years and less than 18 years, ticket price is $5
For anyone above 18 years, price is $10
You can see how the logic of if-elif-else
works :
for
elif
code block, we don’t need to mention that price is $5 for age greater than 4 years but less than or equal to 18 years. Because, if theif
condition passes, the elif and else code block will be ignoredelse
block serves as fallback, if none of above conditions are True
2.4. Using Multiple elif Blocks
To check multiple cognitions , you can use as many
elif
blocks in your code as you like
For example, for the above example, we can create another age group — price is $2 for anyone with age greater than 60 years
2.5. Omitting the else Block
Python does not require an
else
block at the end of anif- elif
chain.
Sometimes an else block is useful; sometimes it is more meaningful to use an additional elif statement that catches the specific condition of interest, in this way you exhaust all the available options that your program should run on:
💡The else
block is a catchall statement. It means, it will only be executed if all earlier conditions are False , which can lead to invalid results in our code. Therefore, to avoid this situation, if you have a specific final condition you are testing for, consider using a final elif
block and omit the else
block.
2.6. Testing Multiple Conditions
Until now, we only executed one set of code and ignore all others. However, we can use more than one if
statements to run more than one block of code. This leads us to define some rules:
If you want only one block of code to run, use an
if- elif-else chain
If more than one block of code needs to run, use a series of independent
if
statements
2.7 STYLING YOUR if
STATEMENTS
if
STATEMENTSPEP 8 recommends to use a single space around comparison operators:
is better than
3. USING if STATEMENTS WITH LISTS
3.1 Checking: an item inside list
Let’s first make a list of few items and store it inside the variable cart_items
Then we can use the for
loop to print the items inside cart_items
if
statement inside the for
loop
if
statement inside the for
loopNow we will use the if-else
statement with in a for
loop
3.2. Checking: List Is Not Empty
It’s useful to check whether a list is empty before running a for
loop. This will avoid getting any errors for performing operation on empty list
Combining two if-else statements block
We can combine the above two examples in the following way:
3.3. Using Multiple Lists
We can use two list to check whether content of one list is available in
second list:
Last updated
Was this helpful?