Page 111 - PortGPT_V2.1_C7_Flipbook
P. 111

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 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:
                                                                        Start
                 if (Test Expressions_1):

                     Indented block 1
                                                                                    True
                 elif (Test Expression_2):                          if condition 1            block 1

                     Indented block 2
                                                                            False
                 elif (Test Expression_3):
                                                                                    True
                     Indented block 3
                                                                    if condition 2            block 2
                 else:
                     Indented block                                        False

                                                                                    True
                                                                    if condition 3            block 3


                                                                            False
                                                                                               block

                                                                                                          Stop




                 Program 7: To check whether a given number is two-digit number, three-digit number or four-
                 digit number.


                     Program7.py
                  File  Edit  Format  Run   Options   Window    Help

                  num = int(input('Enter a number: '))
                  if(9 < num <= 99):
                      print('Two digit number')
                  elif(99 < num <= 999):
                      print('Three digit number')
                  elif(999 < num <= 9999):
                      print('Four digit number')








                                                                                    Conditional Statements in Python  109
   106   107   108   109   110   111   112   113   114   115   116