Basic HTML Version

|  | Table of Contents |  | View Full Version

Page 119 - 2611_SmartGPT Pro V(5.0) C-7
P. 119

    Program 10. To find the sum of the first 10 natural numbers.

                         Program10.py                                                               Output
                      File  Edit  Format   Run    Options   Window    Help                       55

                      sum=0
                      for i in range(0,11):
                           sum+=i
                      print(sum)

                     Program 11. To print the first five multiples of a number.
                         Program11.py                                                             Output

                      File  Edit  Format   Run    Options   Window    Help                     Enter a number: 7

                      num = int(input("Enter a number: "))                                     7 x 1 = 7
                      for i in range(1, 6):                                                    7 x 2 = 14
                          print(num, "x", i, "=", num * i)                                     7 x 3 = 21
                                                                                               7 x 4 = 28
                                                                                               7 x 5 = 35

                     WHILE LOOP IN PYTHON

                     A while loop repeats a set of instructions as long as a given condition is true. It checks the
                     condition before each repetition. If the condition is true, the loop executes; if it’s false, the loop
                     stops and the control moves to the statement outside the loop. It is often used when the number
                     of repetitions is not known in advance.

                     Syntax of while statement:

                     while <condition>:

                          Statement block to be repeated

                                                     Start

                                        False
                                                While condition                                   To indent the code:

                                                        True                                   Short key

                                                   Command                                                 Tab

                                                     Stop

                                                                                               Flow of Control in Python  117

| 114 115 116 117 118 119 120 121 122 123 124 |