少儿Python编程进阶教程:循环(10)

少儿Python编程进阶教程:循环(10)

少儿Python编程进阶教程——循环:先来回顾一下循环的普通用法:

一、逐个打印list项目

fruits = ["apple","banana","cherry"]
for x in fruits:
    print(x)

执行结果:

apple
banana
cherry

二、逐个打印字符串中的字符

for x in "banana":
    print(x)

执行结果:

b
a
n
a
n
a

三、跳出循环(先打印后判断)

fruits = ["apple","banana","cherry"]
for x in fruits:
    print(x)
    if x == "banana":
        break

执行结果:

apple
banana

四、跳出循环(先判断后打印)

fruits = ["apple","banana","cherry"]
for x in fruits:
    if x == "banana":
        break
    print(x)

执行结果:

apple

五、跳过本次循环

fruits = ["apple","banana","cherry"]
for x in fruits:
    if x == "banana":
        continue
    print(x)

执行结果:

apple
cherry

六、range()函数

for x in range(6):
    print(x)
for x in range(2,6):
    print(x)
for x in range(2,30,3):
    print(x)

执行结果:

0
1
2
3
4
5
2
3
4
5
2
5
8
11
14
17
20
23
26
29

七、嵌套循环

adj = ["red","big","tasty"]
fruits = ["apple","banana","cherry"]
for x in adj:
    for y in fruits:
        print(x,y)

执行结果:

red apple
red banana
red cherry
big apple
big banana
big cherry
tasty apple
tasty banana
tasty cherry

八、for循环的高级用法

循环遍历序列时,可以使用enumerate()函数,同时检索位置索引和相应的值。

for i,v in enumerate(['tic','tac','toe']):
    print(i,v)

执行结果:

0 tic
1 tac
2 toe

可以使用reversed()函数反向序列

for i in reversed(range(1,10,2)):
    print(i)

执行结果:

9
7
5
3
1
for i in range(9,1,-2):
    print(i)

执行结果:

9
7
5
3

可使用sorted()函数对序列进行排序,该函数返回一个新的排序列表,同时保持源序列不变。

这与调用basket.sorted() 不同,后者按排序顺序更改原始列表。

basket = ['apple','orange','apple','pear','orange','banana']
for i in sorted(basket):
    print(i)

执行结果:

apple
apple
banana
orange
orange
pear

九、while循环

使用while循环,只要条件为true,我们就可以执行一组语句。

i = 0
while i < 6:
    print(i)
    i+=1

执行结果:

0
1
2
3
4
5

以下是for循环与while循环的区别:

  • while循环需要准备好相关变量,在本例中,我们需要定义一个索引变量i,我们将其设置为0。for循环会自动创建这样的临时变量。
  • 记住要递增i,否则循环将永远继续。

使用break语句,即使while条件为true,我们也可以停止循环。

i = 0
while True:
    if i >=6:
        break
    print(i)
    i+=1

执行结果:

0
1
2
3
4
5

类似地,也可以使用continue语句停止循环的当前迭代,然后继续下一次迭代。

i = 0
while i < 10:
    if i%2 == 1:
        continue
    print(i)
    i += 1

更多Python问题

公众号

关注公众号

x