range() Function can generate a series of numbers . When you need to add some numbers , You can use range() function .
range() The basic syntax of the function is as follows .
range(start, stop)
among ,start Represents the first number in these columns ;stop-1 Represents the last number in the series . It should be noted that , The resulting figures do not include stop.
range() This series of numbers generated by the function is not in the form of a list (list) Types exist , The goal is to save code space .
The following methods can be used to range() The resulting number is converted to a list .
chart 1 Convert to list
From the picture 1 It can be seen that ,range(0,5) The resulting number does not contain 5.
stay 《Python in for How to use statements 》 I mentioned ,for The main function of the statement is to traverse the elements in the container . It can also be in for Use in statement range() The resulting number , Pictured 2 Shown .
chart 2 stay for Use in statement range() The resulting number
As you can see from the above code , stay for Use in statement range() The generated number can be used to control the number of times the statement is executed in a loop .
range() The resulting numbers are stackable (iterable), Can pass sum() Function to sum them , Pictured 3 Shown .
chart 3 Yes range() The resulting numbers are summed
stay “1 Basic grammar ” Mentioned in range() The default step of the number generated by the function syntax is 1, Its step can be specified by the following syntax .
range(start, stop, step)
among ,range() First argument to function start With the second parameter stop And “1 Basic grammar ” Mentioned in range() The basic syntax of a function has the same meaning . The third parameter step Is the specified step , The usage is shown in the figure 4 Shown .
chart 4 Specifies the number of steps
From the picture 4 It can be seen that , here range() The function produces a series of numbers in the form of 2 As stepping .