Python Conditional Statements With example

Conditional Statement

Flow of execution of instruction can be controlled using conditional statements. Conditional statements have some Boolean expression.

Boolean expression can have relational operators or logical operators or both.

Boolean Expression

A boolean expression is an expression it’s result is either true or false. The following examples use the operator ==, which compares two operands and produces True if they are equal and False otherwise:

 >>> 9 == 9
 True
 >>> 9 == 6
 False

True and False are special values that belong to the type bool; they are not strings.

SELECTION

Selection statement is one of the ways in which programmers can change the flow of control in the use of selection control statements.

In order to write useful programs, we almost always need the ability to check conditions and change the behaviour of the program accordingly.

Selection or Conditional statements give us this ability. The simplest form is the if statement:

Python can run on Mac, Windows, and Unix systems and has also been ported to Java and .NET virtual machines.

Types of Selection | Conditional Statements

In python selection can be achieved using four ways

  • if statement
  • The elif Statement
  • if...elif...else
  • Nested if statements

if statements

In order to write useful programs, we almost always need the ability to check conditions and change the behaviour of the program accordingly. Selection or Conditional statements give us this ability. The simplest form is the if statement:

General syntax of if statement

 if TEST EXPRESSION:
 STATEMENT(S) # executed if condition evaluates to True

Here, the program evaluates the TEST EXPRESSION and will execute statement(s) only if the text expression is True. If the text expression is False, the statement(s) is not executed.

A few important things to note about if statements:

1. The colon (:) is significant and required. It separates the header of the compound statement from the body.

2. The line after the colon must be indented. It is standard in Python to use four spaces for indenting.

3. All lines indented the same amount after the colon will be executed whenever the BOOLEAN_EXPRESSION is true.

4. Python interprets non-zero values as True. None and 0 are interpreted as False.

if Statement Flowchart

Example:

 mark = 102
 if mark >= 100:
     print(mark, " is a Not a valid mark.")
 print("This is always printed.")

Output:

 102  is a Not a valid mark.
 This is always printed.

The boolean expression after the if statement (here mark>=100)is called the condition. If it is true, then all the indented statements get executed.

There is no limit on the number of statements that can appear in the body, but there has to be at least one. Occasionally, it is useful to have a body with no statements (usually as a place keeper for code you haven’t written yet). In that case, you can use the pass statement, which does nothing.



The elif Statement

The elif statement is used when the case that you want one thing to happen when a condition is true, and something else to happen when it is false. For that we have if else statement. The syntax looks like this:

General Syntax of it..else statement is

if TEST EXPRESSION:
	STATEMENTS_1  #executed if condition evaluates to True
else:
	STATEMENTS_2  #executed if condition evaluates to False

Each statement inside the if block of an if else statement is executed in order if the test expression evaluates to True.

The entire block of statements is skipped if the test expression evaluates to False, and instead all the statements under the else clause are executed.

Flowchart

There is no limit on the number of statements that can appear under the two clauses of an if else statement, but there has to be at least one statement in each block.

Occasionally, it is useful to have a section with no statements, for code you haven’t written yet. In that case, you can use the pass statement, which does nothing except act as a placeholder.

 if True: #This is always true
 	 pass #so this is always executed, but it does nohing
 else:
  	 pass

Example:

 age=21			#age=17
 if age >= 18:
     print("Eligible to vote")
 else:
     print("Not Eligible to vote")

Output:

 Eligible to vote

In the above example, when age is greater than 18, the test expression is true and body of if is executed and body of else is skipped.

If age is less than 18, the test expression is false and body of else is executed and body of if is skipped.

If age is equal to 18, the test expression is true and body of if is executed and body of else is skipped.



if...elif...else

Sometimes there are more than two possibilities and we need more than two branches. One way to express a computation like that is a chained conditional.

The syntax looks like this:

General Syntax of if..elif...else statement is

 if TEST EXPRESSION1:
 	STATEMENTS_A 
 elif TEST EXPRESSION2:
	 STATEMENTS_B
 else:
 	STATEMENTS_C

The elif is short for else if. It allows us to check for multiple expressions.

If the condition for if is False, it checks the condition of the next elif block and so on. If all the conditions are False, body of else is executed.

Only one block among the several if...elif...else blocks is executed according to the condition. The if block can have only one else block. But it can have multiple elif blocks.

Flowchart

Each condition is checked in order. If the first is false, the next is checked, and so on. If one of them is true, the corresponding branch executes, and the statement ends. Even if more than one condition is true, only the first true branch executes.

Example:

time=17  #time=10, time=13, time=17, time=22
if time<12:
    print("Good Morning")
elif time<15:
    print("Good Afternoon")
elif time<20:
    print("Good Evening")
else:
    print("Good Night")

Output:

 Good Evening

When variable time is less than 12, Good Morning is printed. If time is less than 15, Good Afternoon is printed. If time is less than 20, Good Evening is printed. If all above conditions fails Good Night is printed.



Nested Conditionals

One conditional can also be nested within another. ie, We can have a if...elif...else statement inside another if...elif...else statement. This is called nesting in computer programming.

Any number of these statements can be nested inside one another. Indentation is the only way to figure out the level of nesting.

General Syntax of Nested if..else statement is

 if TEST EXPRESSION1:
 	if TEST EXPRESSION2:
 		STATEMENTS_B
 	else:
 		STATEMENTS_C
 else:
 	if TEST EXPRESSION3:
 		STATEMENTS_D
 	else:
 		STATEMENTS_E

Flowchart

The outer conditional contains two branches. Those two branches contain another if… else statement, which has two branches of its own. Those two branches could contain conditional statements as well.

Example:

 a=10
 b=20
 c=5
 if a>b:
     if a>c:
         print("Greatest number is ",a)
     else:
         print("Greatest number is",c)
 else:
     if b>c:
         print("Greatest number is ",b)
     else:
         print("Greatest number",c)

Output:

 Greatest number is  20

Although the indentation of the statements makes the structure apparent, nested conditionals very quickly become difficult to read. In general, it is a good idea to avoid them when yo can.