Page 129 - ComputerGenius_V2.1_Class8
P. 129

if-else Statement

                 The if…else statement checks for a condition.
                 l    The ‘if-else’ statement evaluates the test expression and will execute the body only if the test

                   condition is True.


                 l   If the condition is False, the body of ‘else’ is executed. Indentation is used to separate the
                   blocks.
                 Syntax:
                   if (Condition1):
                     Statement1
                     . . . . . . . . . .
                   else:
                     Statement2
                     . . . . . . . . . .

                 Example 3: Python if-else Statement
                 Program:
                   num = 3
                   if num > 0:
                     print("Positive number.")
                   else :
                     print("Negative number.")

                 Output:
                   Positive number.

                 Description:

                 In the above program, we checked whether a number is greater than zero. If the condition gets true:
                 The statements inside the if block gets executed, otherwise, the statements inside the else block
                 gets executed.

                 Example 4: Python if-else Statement
                 Program:
                   num = int(input("Enter a number : "))

                   if num > 0:
                       print(num,"is a positive number.")
                   else:
                       print(num,"is a negative number.")
                   print("This is outside if-else.")

                 Output 1:
                   Enter a number : 12
                   12 is a positive number.

                   This is outside if-else.

                                                                                    Control Flow Statements   127
   124   125   126   127   128   129   130   131   132   133   134