菜鸟教程 -- 学的不仅是技术,更是梦想!

Python 基础教程
(追記) (追記ここまで)

Python 循环嵌套

Python 语言允许在一个循环体里面嵌入另一个循环。

Python for 循环嵌套语法:

foriterating_varinsequence: foriterating_varinsequence: statements(s)statements(s)

Python while 循环嵌套语法:

whileexpression: whileexpression: statement(s)statement(s)

你可以在循环体内嵌入其他的循环体,如在while循环中可以嵌入for循环, 反之,你可以在for循环中嵌入while循环。

实例:

以下实例使用了嵌套循环输出2~100之间的素数:

实例

#!/usr/bin/python# -*- coding: UTF-8 -*-i = 2while(i < 100): j = 2while(j <= (i/j)): ifnot(i%j): breakj = j + 1if(j > i/j) : printi, " 是素数"i = i + 1print"Good bye!"

以上实例输出结果:

2 是素数
3 是素数
5 是素数
7 是素数
11 是素数
13 是素数
17 是素数
19 是素数
23 是素数
29 是素数
31 是素数
37 是素数
41 是素数
43 是素数
47 是素数
53 是素数
59 是素数
61 是素数
67 是素数
71 是素数
73 是素数
79 是素数
83 是素数
89 是素数
97 是素数
Good bye!
AI 思考中...

5 篇笔记 写笔记

  1. #0

    蓝色的天空

    302***[email protected]

    95

    使用循环嵌套来获取100以内的质数

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
    num=[];
    i=2
    for i in range(2,100):
     j=2
     for j in range(2,i):
     if(i%j==0):
     break
     else:
     num.append(i)
    print(num)
    

    蓝色的天空

    302***[email protected]

    9年前 (2017年04月21日)
  2. #0

    zero

    562***[email protected]

    34

    ×ばつ字塔的实现

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
    #*字塔
    i=1
    #j=1
    while i<=9:
     if i<=5:
     print ("*"*i)
     elif i<=9 :
     j=i-2*(i-5)
     print("*"*j)
     i+=1
    else :
     print("")
    

    zero

    562***[email protected]

    9年前 (2017年06月19日)
  3. #0

    (+__+)

    lk0***[email protected]

    26

    冒泡排序

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
    array = [9,2,7,4,5,6,3,8,1,10]
    L = len(array)
    for i in range(L):
     for j in range(L-i):
     if array[L-j-1]<array[L-j-2]:
     array[L-j-1],array[L-j-2]=array[L-j-2],array[L-j-1]
    for i in range(L):
     print array[i],

    (+__+)

    lk0***[email protected]

    9年前 (2017年07月25日)
  4. #0

    C6H8O7

    235***[email protected]

    19
    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
    #求区间[a,b]内的质数
    a = 1000 #起始
    b = 10000 #结束
    E = []
    for num in range(a,b+1):
     snum = int(num*0.5+1)
     for i in range(2,snum): 
     if num%i == 0: 
     break 
     else: 
     E.append(num)
    print a,'到',b,'的质数有',E
    print a,'到',b,'有',len(E),'个质数' 

    C6H8O7

    235***[email protected]

    9年前 (2017年09月30日)
  5. #0

    boweiqingfeng

    yyx***[email protected]

    43

    选择排序:

    array = [8,2,6,3,4,5,7,1,10,9]
    L=len(array)
    for i in range(1,L):
     temp = array[i]
     array.remove(array[i])
     for j in range(i):
     if array[j]>temp:
     array.insert(j,temp)
     break
     else:
     array.insert(i,temp)
    print(array)

    boweiqingfeng

    yyx***[email protected]

    8年前 (2018年12月04日)

点我分享笔记

  • 昵称 (必填)
  • 邮箱 (必填)
  • 引用地址

AltStyle によって変換されたページ (->オリジナル) /