程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

How to use the range() function in Python

編輯:Python

range() Function can generate a series of numbers . When you need to add some numbers , You can use range() function .

1 Basic grammar

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.

2 Usage method

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 .

2.1 take range() The resulting number is converted to a list

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.

2.2 stay for Use in statement range() The resulting number

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 .

2.3 Yes range() The resulting numbers are summed

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

3 Specify the number of steps

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 .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved