Page 135 - Plus_V2.2_C7_Flipbook
P. 135

On running the above program, we get the following output:





























                      The if…elif…else Ladder

                 The if…elif…else ladder is another type of if statement. It helps us to test multiple conditions and
                 follows a top-down approach. In this, as soon as the condition of the if evaluates to be true, the
                 indented block associated with that ‘if’ is executed, and the rest of the ladder is avoided. If none of the
                 conditions evaluates to true, then the final else statement gets executed.

                 The syntax of if...elif...else ladder is shown below:
                 Syntax:


                 if (Test Expressions_1):
                     Indented block 1
                                                                                  True
                 elif (Test Expression_2):                     Test Expression 1         Statement 1
                     Indented block 2
                                                                        False
                 elif (Test Expression_3):
                     Indented block 3                                             True
                                                               Test Expression 2        Statement 2
                 else:
                     Indented block                                     False


                                                                                  True
                                                               Test Expression 3         Statement 3


                                                                        False           Body of else




                                                                                                Statement just below
                                                                                                 if...elif...else ladder




                                                                                    Conditional Statements in Python  133
   130   131   132   133   134   135   136   137   138   139   140