11. Conditional Statements
What are Conditional Statements?
We have often used conditional statements in our daily life, such as :
if it rains ,i will go to office.
Syntax:
In [ ]:
if expression:
statement 
Above Figure Shows , Actions or decisions based on the Condition. If the condition is True, i will not go to office. Here are some Examples for if statement:
How to Find if a number is even?
In [2]:
Indentation:
Python indentation is a way of telling python intrepreter that the group of statements/code/instrtuctions belong to a particular block.
In more simpler terms , indentation is nothing but a bunch of spaces or tabs signifying a particular line of code belongs to a same group.
Now You saw what will happen if the condition is true in above case. All the code with same indentation will run. But what will happen if the condition is False?
In [3]:
So, Here the codes with same indentation did not run, it shows that if condition is True, Body of if will run. Body of if (Codes written under if statement by using indentation.), if Condition is False, Body of if will not run.
Note:We generally use Tab to define indentations. One Tab means 4 spaces.
if-else statement:
The if-else statement is similar to if statement except the fact that, it also provides the block of the code for the false case of the condition to be checked.
If the condition provided in the if statement is false, then the else statement will be executed.
For Example : . if coffee house is open i'll go there else i will be at home.
In [ ]:
To find if a number is even or odd:
In [2]:
In [3]:
if-elif statement:
The elif statement enables us to check multiple conditions and execute the specific block of statements depending upon what condition is True.
Syntax:
In [ ]:

So , elif - statement , in more simpler terms runs body of first if or elif statement with true condition and if any of the condition is not true , body of else executes.
For Example:
Program to find grade of a student based on marks:
In [1]:
Nested if:
There may be a situation when you want to check for another condition after a condition resolves to true. In such a situation, you can use the nested if construct.
In more simpler terms, Nested if is actually if statement under an if statement.
Syntax:
In [ ]:

Program to find Largest Number among three numbers:
In [1]:
Note: Run above code in your editor and change values to see , how this code is working.
Branching using Conditional Statements in Python

This tutorial covers the following topics:
Branching with
if,elseandelifNested conditions and
ifexpressionsIteration with
whileloopsIterating over containers with
forloopsNested loops,
breakandcontinuestatements
Branching with if, else and elif
if, else and elifOne of the most powerful features of programming languages is branching: the ability to make decisions and execute a different set of statements based on whether one or more conditions are true.
The if statement
In Python, branching is implemented using the if statement, which is written as follows:
The condition can be a value, variable or expression. If the condition evaluates to True, then the statements within the if block are executed. Notice the four spaces before statement1, statement2, etc. The spaces inform Python that these statements are associated with the if statement above. This technique of structuring code by adding spaces is called indentation.
Indentation: Python relies heavily on indentation (white space before a statement) to define code structure. This makes Python code easy to read and understand. You can run into problems if you don't use indentation properly. Indent your code by placing the cursor at the start of the line and pressing the
Tabkey once to add 4 spaces. PressingTabagain will indent the code further by 4 more spaces, and pressShift+Tabwill reduce the indentation by 4 spaces.
For example, let's write some code to check and print a message if a given number is even.
We use the modulus operator % to calculate the remainder from the division of a_number by 2. Then, we use the comparison operator == check if the remainder is 0, which tells us whether the number is even, i.e., divisible by 2.
Since 34 is divisible by 2, the expression a_number % 2 == 0 evaluates to True, so the print statement under the if statement is executed. Also, note that we are using the string format method to include the number within the message.
Let's try the above again with an odd number.
In [4]:
As expected, since the condition another_number % 2 == 0 evaluates to False, no message is printed.
The else statement
We may want to print a different message if the number is not even in the above example. This can be done by adding the else statement. It is written as follows:
If condition evaluates to True, the statements in the if block are executed. If it evaluates to False, the statements in the else block are executed.
In [5]:
In [6]:
In [7]:
In [8]:
Here's another example, which uses the in operator to check membership within a tuple.
In [9]:
In [10]:
In [11]:
The elif statement
Python also provides an elif statement (short for "else if") to chain a series of conditional blocks. The conditions are evaluated one by one. For the first condition that evaluates to True, the block of statements below it is executed. The remaining conditions and statements are not evaluated. So, in an if, elif, elif... chain, at most one block of statements is executed, the one corresponding to the first condition that evaluates to True.
In [12]:
In [13]:
In the above example, the first 3 conditions evaluate to False, so none of the first 3 messages are printed. The fourth condition evaluates to True, so the corresponding message is printed. The remaining conditions are skipped. Try changing the value of today above and re-executing the cells to print all the different messages.
To verify that the remaining conditions are skipped, let us try another example.
In [14]:
Note that the message 15 is divisible by 5 is not printed because the condition a_number % 5 == 0 isn't evaluated, since the previous condition a_number % 3 == 0 evaluates to True. This is the key difference between using a chain of if, elif, elif... statements vs. a chain of if statements, where each condition is evaluated independently.
In [16]:
Using if, elif, and else together
You can also include an else statement at the end of a chain of if, elif... statements. This code within the else block is evaluated when none of the conditions hold true.
In [17]:
In [19]:
In [20]:
Non-Boolean Conditions
Note that conditions do not necessarily have to be booleans. In fact, a condition can be any value. The value is converted into a boolean automatically using the bool operator. This means that falsy values like 0, '', {}, [], etc. evaluate to False and all other values evaluate to True.
In [21]:
In [22]:
In [23]:
In [24]:
Nested conditional statements
The code inside an if block can also include an if statement inside it. This pattern is called nesting and is used to check for another condition after a particular condition holds true.
In [25]:
In [26]:
Notice how the print statements are indented by 8 spaces to indicate that they are part of the inner if/else blocks.
Nested
if,elsestatements are often confusing to read and prone to human error. It's good to avoid nesting whenever possible, or limit the nesting to 1 or 2 levels.
Shorthand if conditional expression
A frequent use case of the if statement involves testing a condition and setting a variable's value based on the condition.
Python provides a shorter syntax, which allows writing such conditions in a single line of code. It is known as a conditional expression, sometimes also referred to as a ternary operator. It has the following syntax:
It has the same behavior as the following if-else block:
Let's try it out for the example above.
In [28]:
In [29]:
Statements and Expressions
The conditional expression highlights an essential distinction between statements and expressions in Python.
Statements: A statement is an instruction that can be executed. Every line of code we have written so far is a statement e.g. assigning a variable, calling a function, conditional statements using
if,else, andelif, loops usingforandwhileetc.Expressions: An expression is some code that evaluates to a value. Examples include values of different data types, arithmetic expressions, conditions, variables, function calls, conditional expressions, etc.
Most expressions can be executed as statements, but not all statements are expressions. For example, the regular if statement is not an expression since it does not evaluate to a value. It merely performs some branching in the code. Similarly, loops and function definitions are not expressions (we'll learn more about these in later sections).
As a rule of thumb, an expression is anything that can appear on the right side of the assignment operator =. You can use this as a test for checking whether something is an expression or not. You'll get a syntax error if you try to assign something that is not an expression.
In [30]:
In [31]:
The pass statement
if statements cannot be empty, there must be at least one statement in every if and elif block. You can use the pass statement to do nothing and avoid getting an error.
In [33]:
In [34]:
Questions for Revision
Try answering the following questions to test your understanding of the topics covered in this notebook:
What is branching in programming languages?
What is the purpose of the
ifstatement in Python?What is the syntax of the
ifstatement? Give an example.What is indentation? Why is it used?
What is an indented block of statements?
How do you perform indentation in Python?
What happens if some code is not indented correctly?
What happens when the condition within the
ifstatement evaluates toTrue? What happens if the condition evaluates forfalse?How do you check if a number is even?
What is the purpose of the
elsestatement in Python?What is the syntax of the
elsestatement? Give an example.Write a program that prints different messages based on whether a number is positive or negative.
Can the
elsestatement be used without anifstatement?What is the purpose of the
elifstatement in Python?What is the syntax of the
elifstatement? Give an example.Write a program that prints different messages for different months of the year.
Write a program that uses
if,elif, andelsestatements together.Can the
elifstatement be used without anifstatement?Can the
elifstatement be used without anelsestatement?What is the difference between a chain of
if,elif,elif… statements and a chain ofif,if,if… statements? Give an example.Can non-boolean conditions be used with
ifstatements? Give some examples.What are nested conditional statements? How are they useful?
Give an example of nested conditional statements.
Why is it advisable to avoid nested conditional statements?
What is the shorthand
ifconditional expression?What is the syntax of the shorthand
ifconditional expression? Give an example.What is the difference between the shorthand
ifexpression and the regularifstatement?What is a statement in Python?
What is an expression in Python?
What is the difference between statements and expressions?
Is every statement an expression? Give an example or counterexample.
Is every expression a statement? Give an example or counterexample.
Last updated