Introduction to Python : The if conditional

The if conditional

The 'if' condition defines a block of code that is executed only when the result of a comparison or logical expression is True. 'if' conditionals are very important since they provide a means to have alternative paths within a program through the 'elif' and 'else' blocks. Examples

if 5 > 4:
   print ("Yes 5 is greater")
   print ("No 5 is not greater")

The program above first evaluates the comparison expression (5 > 4) which is True and therefore moves into the code block that prints 'Yes 5 is greater'. The 'else' block is skipped since only one block is executed in a 'if, else' expression.

if 2 > 3 or 4 > 5:
   print ("First block")
elif 3 < 8 and 8 > 4:
   print ("Second block")
   print ("Last block")

The program above will output 'Second block' since the first 'if' condition evaluates to false and therefore skipped to the second condition which evaluates to True. The last block is not executed either since only one block is executed in an 'if...elif...else' expression.



course logo
Introduction to Python
Number of sections:
Content length:
Delivery formats: