Basic HTML Version

|  | Table of Contents |  | View Full Version

Page 144 - 2632_CodeMind
P. 144

    Using the range( ) Function

                     The range() function is an in-built function of Python. This function generates a list which is a sequence
                     type. A sequence is a succession of values bound together by a single name. The range() function is
                     used in the for loop to iterate over the numbers.

                     The general syntax of using the range() function is given below.
                       range(n): Generates a set of whole numbers starting from 0 to (n–1).

                       Example: range(6) is equivalent to [0, 1, 2, 3, 4, 5].
                       range(start, stop): Generates a set of whole numbers starting from ‘start’ to ‘stop–1’.
                       Example: range(4, 9) is equivalent to [3, 4, 5, 6, 7, 8].

                        range(start,  stop, step_size): By  default,  the value         Just as the heart repeatedly
                                                                                           pumps blood, iteration
                       of the step_size  =  1 and numbers are generated  with             in programming involves
                       a difference  of  1. However, we can generate  numbers            repeatedly running a set of
                       by  specifying  the  value of step_size  according  to  our              instructions.
                       requirement.
                        Example: range(1, 14, 2) is equivalent to [1, 3, 5, 7, 9,11,13].

                                       Imagine, you possess the power of jump statement, allowing you to leap to any
                                       part of the universe. Where would you jump to and what quests or missions would
                                       you undertake in each dimension?

                      Program 1: To print whole numbers from 0 to 7 using only stop value.

                         Program1.py

                      File  Edit  Format   Run   Options   Window     Help

                      for i in range (8):
                        print(i)

                     You will get the following output:

                         Output

                      0
                      1
                      2
                      3
                      4
                      5
                      6
                      7

                                                                                                      Loops in Python  143

| 139 140 141 142 143 144 145 146 147 148 149 |