Previous | Next


The condition statement allow the Python program to decide whether or not to execute a block of statements based on the return boolean value from condition expression.

if clauses

if <expression>:
  <block of statements>

Let’s try with the following example:

value = 100
if value > 50:
  print 'Value is greater than 50'

The if condition statement evaluate a given expression (value > 50). It print a statement (‘Value is greater than 50’) if the expression return true.

else clauses

if <expression>:
  <block of statements>
else:
  <block of statements>

Let’s try with the following example:

value = 100
if value > 50:
  print 'Value is greater than 50'
else:
  print 'Value is less than 50'

The if condition statement evaluate a given expression (value > 50). It print statement (‘Value is greater than 50’) if the expression return true. Otherwise, it print statement (‘Value is less than 50’) if the expression return false.

elif clauses

if <expression>:
  <block of statements>
elif <expression>::
  <block of statements>
else:
  <block of statements>

Let’s try with the following example:

value = 35
if value > 50:
  print 'Value is greater than 50'
elif value > 30:
  print 'Value is greater than 30'
else:
  print 'Value is less than 30'

The first if condition statement evaluate a given expression (value > 50). It print statement (‘Value is greater than 50’) if the expression return true. If it return false false, the program continue with second if condition statement with a given expression (value > 30). It print statement (‘Value is greater than 30’) if the expression return true. Otherwise, it print statement (‘Value is less than 30’) if the expression return false.

Nested if condition

if <expression>:
  if <expression>:
    <block of statements>
  else:
    <block of statements>
else:
    <block of statements>

Let’s try with the following example:

first_name = 'john'
last_name = 'paw'
if first_name == 'john':
  if last_name == 'paw':
    print 'I am John Paw!'
  else:
    print 'I am John!'
else:
  print 'I am Python'

The if condition statement evaluate a given expression (first_name == ‘john’). If it return false, it print a statement (‘I am Python’). Otherwise, it continue with the nested if condition statement by evaluate a given expression (last_name == ‘paw’). It print the statement (‘I am John Paw!’) if it return true. Otherwise, it print the statement (‘I am John!’).

 


Previous | Next