python range
输出变量
在函数中输出多个变量的最佳方式print()是用逗号分隔它们,甚至支持不同的数据类型:
x = 5
y = "John"
print(x, y)
在print()函数中,当你尝试用+ 操作符组合字符串和数字时,Python 会报错:
x = 5
y = "John"
print(x + y)
相同变量时,逗号分割和+号都可以拼接。
Python中的range
-
range
range类似于列表,是自定制数字范围的列表,里面的元素只能是数字。一般在for循环中。
-
函数语法

range取值(顾头不顾尾)
迭代取值

- 索引取值
- 切片取值

"""生成一个range类型的可迭代对象:""" >>> a = range(3) >>> type(a) range """可以看到a的类型是range,有点懵,看下帮助文档""" >>> print(a.__doc__) range(stop) -> range object range(start, stop[, step]) -> range object Return an object that produces a sequence of integers from start (inclusive) to stop (exclusive) by step. range(i, j) produces i, i+1, i+2, ..., j-1. start defaults to 0, and stop is omitted! range(4) produces 0, 1, 2, 3. These are exactly the valid indices for a list of 4 elements. When step is given, it specifies the increment (or decrement). """文档介绍了一下range的用法,并没有细说""" """接着在PyCharm里用`.`的方法可以看到,a具有方法:start,stop,step"" >>> a.start 0 >>> a.stop 3 >>> a.step 1 """ 接着对a进行迭代 因为a是可迭代对象,需要使用iter()函数将a转为迭代器,接着使用next()方法进行迭代取值 """ >>> b = iter(a) """现在b终于是range可迭代对象了,现在用type查看一下:""" >>> type(b) range_iterator """迭代""" >>> next(b) 0 >>> next(b) 1 >>> next(b) 2 >>> next(b) StopIteration Traceback (most recent call last) <ipython-input-57-adb3e17b0219> in <module>() ----> 1 next(b) 到这里报错,因为迭代已经结束
参考网站:
https://blog.csdn.net/hi_xtm/article/details/108809391
https://www.w3schools.com/python
https://www.jianshu.com/p/9962c3352cac
浙公网安备 33010602011771号