Basic HTML Version

|  | Table of Contents |  | View Full Version

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

    PYTHON ITERATIVE STATEMENTS

                     Iteration means repeating a set of instructions again and again. It is a flow of control that allows
                     a part of the code to run multiple times without writing it again each time. In many programs, we
                     often need to repeat certain actions. Instead of copying the same code many times, we use loops
                     to do it automatically.

                     Using loops helps save time, reduce mistakes and make the code shorter and cleaner.
                     Python provides two main types of loops: the for loop, which repeats a block of code for each item

                     in a sequence or for a specific number of iterations and the while loop, which repeats a block of
                     code as long as a condition is true.
                     range() function

                     The range() function is a built-in function in Python that generates a sequence of numbers.

                     The range() function is most commonly used with the for loop to repeat tasks a specific number
                     of times.

                     Syntax of the range() function:

                     range(start, stop, step)
                     where,

                       start: This is the optional value where the sequence begins. If you don’t specify it, Python will
                       automatically start from 0.
                       For example, range(5) is treated as range(0, 5) and generates: [0, 1, 2, 3, 4].

                       stop: This is the mandatory value at which the sequence ends, but it is not included in the
                       result.

                       For example, range(2, 6) gives: [2, 3, 4, 5] (6 is excluded).
                       step: This optional value defines how much the value should increase or decrease each time.

                       The default step value is 1, which means the numbers go up one at a time. You can also use a
                       negative step value to create a descending sequence.

                       For example:  range(10, 2, -2) gives [10, 8, 6, 4].
                                      range(2, 8, 3) gives [2, 5].

                          PURE       Python has no limit on variable name length, but line lengths should be kept under 79
                          FACT       characters for better readability.

                                                                                               Flow of Control in Python  115

| 112 113 114 115 116 117 118 119 120 121 122 |