学了几天的python,觉得python特别简单,不用标点符号,不用大括号,只要缩进正确就可以,语法也很简洁。
range函数
python range() 函数可创建一个整数列表,一般用在 for 循环中。
函数语法
range(start, stop[, step])
参数说明:
- start: 计数从 start 开始。默认是从 0 开始。例如range(5)等价于range(0, 5);
- stop: 计数到 stop 结束,但不包括 stop。例如:range(0, 5) 是[0, 1, 2, 3, 4]没有5
- step:步长,默认为1。例如:range(0, 5) 等价于 range(0, 5, 1)
关于for的两种用法
1、作为循环使用
输出1~10:
for i in range(10):
print(i, end=" ")
2、作为遍历使用(迭代器)
Python for循环可以遍历任何序列的项目,如一个列表或者一个字符串。
str = 'abcdef'
for item in str:
print(item, end=' ')
# 输出:a b c d e f
list = ['1', 2, True, 'abc']
for item in list:
print(item, end=' ')
# 输出:1 2 True abc
其实本质上是一种用法,for的本质就是作为一个迭代器去遍历一个集合,将集合中的内容依次遍历。