当前位置:   article > 正文

python3内置函数range()心得_python3 range

python3 range

python3内置函数range()心得

本文环境:Win 7 (64-bit) + python 3.7.6 (32 bit) + Thonny 3.2.6

概念

range()是python 3的内置函数(Built-in Functions),它返回一个 range 对象的整数序列,可以设定这个序列的起点、终点和步长。

语法

range(start,stop,step = 1)
参数说明:
参数1:start 起点包含,一个整数,可以是负数。可以省略。
参数2:stop 终点不包含,一个整数,可以是负数。不能省略。
参数3:step = 1 步长,一个整数,可以是负数。可以省略,省略时默认步长是 1 。步长:从以当前元素为起点0,加上步长值,再次输出。

当参数1 start 起点,参数3 step 步长同时省略后,可以写成如下形式:
range(stop)
参数1:start 起点包含,省略时默认值是 0 。
参数2:stop 终点不包含,一个大于0的正整数。不能省略。
参数3:step = 1 步长,省略时默认步长是 1 。

返回值

返回一个 range 对象的整数序列。

例子

指定起点、终点、步长 range(start,stop,step)

# python内建函数 range() 训练
temp = range(-5,6,3)
print(temp) # temp是range对象,无法打印输出
print(type(temp)) # 显示确认temp是range对象
print(list(temp)) # 可以把range对象转换为列表对象输出
  • 1
  • 2
  • 3
  • 4
  • 5
'
运行

结果

>>> %Run test.py
range(-5, 6, 3)
<class 'range'>
[-5, -2, 1, 4]
>>> 
  • 1
  • 2
  • 3
  • 4
  • 5

结果分析
在这里插入图片描述

指定步长为负数生成从大到小的对象

# python内建函数 range() 训练
temp = range(6,-5,-2)
print(temp) # temp是range对象,无法打印输出
print(type(temp)) # 显示确认temp是range对象
print(list(temp)) # 可以把range对象转换为列表对象输出
  • 1
  • 2
  • 3
  • 4
  • 5
'
运行

结果

>>> %Run test.py
range(6, -5, -2)
<class 'range'>
[6, 4, 2, 0, -2, -4]
>>>
  • 1
  • 2
  • 3
  • 4
  • 5

结果分析
在这里插入图片描述

参数3 step 步长使用负数时,由于负数步长是从参数1 start 起点开始,向数轴的左侧索引,所以参数1 start 起点的值要大于参数2 stop 终点的值。

只指定参数2 stop 终点

# python内建函数 range() 训练
temp = range(10)
print(temp) # temp是range对象,无法打印输出
print(type(temp)) # 显示确认temp是range对象
print(list(temp)) # 可以把range对象转换为列表对象输出
  • 1
  • 2
  • 3
  • 4
  • 5
'
运行

结果

>>> %Run test.py
range(0, 10)
<class 'range'>
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> 
  • 1
  • 2
  • 3
  • 4
  • 5

Python官网链接

https://docs.python.org/zh-cn/3/library/functions.html#func-range
https://docs.python.org/zh-cn/3/library/functions.html#func-range

Python官网内容截图中文

在这里插入图片描述

Python官网内容截图英文

在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/空白诗007/article/detail/818841
推荐阅读
相关标签
  

闽ICP备14008679号