Python中的循环

There are three types of loops in python:

python中有三种循环类型:

  1. Condition Controlled Loops

    条件控制循环

  2. Range Controlled Loops

    范围控制回路

  3. Collection Controlled Loops

    集合控制循环

1)条件控制循环 (1) Condition Controlled Loops)

In Condition controlled Loops, there is condition(expression) that controls the loop. In python there is 1 loop falls under this category.

在条件控制的循环中,存在控制循环的条件(表达式)。 在python中,有1个循环属于此类别。

a. while Loop

一个。 while循环

a=1
while a<=10:
    print(a)
    a=a+1

Output

输出量

1
2
3
4
5
6
7
8
9
10

b. Do Loop (Not Present in Python)

b。 执行循环(Python中不存在)

In Python Do While is NOT present, but we can convert while loop to work as do while loop.

在Python中,Do While不存在,但是我们可以将while循环转换为while循环。

a=1
while True:
    print(a)
    a=a+1
    if a>10:
        break

Output

输出量

1
2
3
4
5
6
7
8
9
10

2)范围控制回路 (2) Range Controlled Loops)

For loop is used for implementation of Range()

For循环用于Range()的实现

There are three ways to use Range():

有三种使用Range()的方法:

1. Range with 1 Parameter [range(end)] [start=0, step=1]

1.具有1个参数[range(end)]的范围[start = 0,step = 1]

for i  in range(10):
    print(i,end="\t")

Output

输出量

0       1       2       3       4       5       6       7       8       9

2. Range with 2 Parameter [range(start,end)] [step=1]

2.具有2个参数的范围[range(start,end)] [step = 1]

for i  in range(1,10):
    print(i,end="\t")

Output

输出量

0       1       2       3       4       5       6       7       8       9

3. Range with 3 Parameter [range(start,end,step)]

3.具有3个参数的范围[范围(开始,结束,步骤)]

for i  in range(1,10,3):
    print(i,end="\t")

Output

输出量

1       4       7


3)集合控制循环 (3) Collection Controlled Loops)

Collection controlled loops are also implemented with the help of for loop.We need a collection object as a source. Python have various collection class like: list, tuple, set, dict.

集合控制的循环也可以通过for循环来实现。我们需要一个集合对象作为源。 Python具有各种收集类,例如:list,tuple,set,dict

a. with List

一个。 与清单

# with list
data = [12,45,67,23,15]
for item in data:
    print(item) 

Output

输出量

12
45
67
23
15

b. with tuple

b。 与元组

# with tuple
data = (12,45,67,23,15)
for item in data:
    print(item) 

Output

输出量

12
45
67
23
15

c. with set

C。 套装

# with set
data = {12,45,67,23,15}
for item in data:
    print(item)

Output

输出量

12
45
67
23
15

d. with dict(dictionary)

d。 与字典(字典)

# with dictionaies
data = {"item1":12,"item2":45,"item3":67,"item4":23,"item5":15}
for item in data:
    print("data["+item+"] = "+str(data[item])) 

Output

输出量

data[item3] = 67
data[item2] = 45
data[item1] = 12
data[item5] = 15
data[item4] = 23


翻译自: https://www.includehelp.com/python/loops.aspx

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值