Python中的for循环

while循环:在任何条件为真的情况下重复执行一个代码块
for循环:可用在为一个集合(序列或其他可迭代对象)的每个元素都执行一个代码块,它必while循环更简洁

words = ["a","b",123,"d"]
for word in words:
    print(word)#将列表words中的元素打印出来

numbers = [1,2,3,4,5]
for number in numbers:
    print(number)


Output:
a
b
123
d
1
2
3
4
5

Python将迭代某范围的数字打包成一个函数供使用
range()函数

for i in range(10):
    print(i)#打印0-910个数字,即循环10次

Output:
0
1
2
3
4
5
6
7
8
9

它默认下限为0,需要我们提供上限;同时我们也可以改变下限,中间用逗号隔开

for i in range(10,20):
    print(i)#打印10-1910个数字,即循环10次
Output:
10
11
12
13
14
15
16
17
18
19

关于循环对象的数据类型:
取决于集合中对象本身

for i in range(3):
    print(type(i))

Output:
<class 'int'>
<class 'int'>
<class 'int'>

words = ["a","b",1,"asd"]
for word in words:
    print(type(word))
Output:
<class 'str'>
<class 'str'>
<class 'int'>
<class 'str'>


关于在for前面加上变量或函数
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值