Home  >  Article  >  Backend Development  >  python basics-loop

python basics-loop

巴扎黑
巴扎黑Original
2016-12-03 09:54:141004browse

for loop:

a = [11,22,33,44]

for i in a:
print (i)

result:

11
22
33
44

while loop:

i=0
while i < 3: #i<3 is the loop condition. When the condition is true, the following loop body will be executed; when the condition is false, it will not be executed.
print (i)
i += 1

Result:

0
1
2

break and Continue:

i= 0
while i < 10:
print ("i->:",i)
if i == 5:
break #When i==5, exit all loops
i += 1

Result:

i->: 0
i->: 1
i->: 2
i->: 3
i->: 4
i->: 5
x=0
while x < 9:
for x in range(0,10):
if x ==6:
continue #when x== At 6 o'clock, jump out of the current loop and continue the next loop
                                                                  print("x->:", x)

Result:

x->: 0
x->: 1
x->: 2
x->: 3
x->: 4
x->: 5
x->: 7 #missingx->: 6
x->: 8
x->: 9

Others:

enumrate:

a = ["aa","bb","cc","dd"]

for i in enumerate(a,5): #The default number starts from 0, Can be changed manually
Print (i)

Result:

(5, 'aa')
(6, 'bb')
(7, 'cc')
(8, 'dd')

range :

1,

for n in range(1, 10):
print (n)

Result:

1
2
3
4
5
6
7
8
9

2 ,

for x in range(0,20,4):
print (x)

Result:

0
4
8
12
16
#Use 4 as step and print


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:python basics-listNext article:python basics-list