Page 129 - Computer Genius Class 08
P. 129

Syntax:
                 if (Test Expression):
                   Indented statement block
                 #  if block  ends here

                 Example 1: Python if Statement
                   num = 3
                   if num > 0:

                     print(num,"is a positive number.")
                   print("This is always printed.")

                 Output:
                   3 is a positive number.

                   This is always printed.
                 Description:

                 In the above program, we have checked a condition using ‘If’ Statement. If the statement turns out
                 to be true, the statement after indentation gets executed.
                 Example 2: Python if Statement
                   num = 3
                   if num > 0:  # Condition 1

                     print(num,"is a positive number.")
                   print("This is always printed.")
                   num = - 1
                   if num > 0:  # Condition 2

                     print(num,"is a positive number.")
                   print("This number not greater than 0")

                 Output:
                   3 is a positive number.
                   This is always printed.

                   This number not greater than 0
                 Description:

                 In the above program, we have checked a condition using the ‘If’ Statement. If the statement gets
                 false, the statement after the indentation gets executed.
                 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.


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