Python for循环语句

来自:http://www.runoob.com/python/python-for-loop.html

Python for 循环语句

Python for循环可以遍历任何序列的项目,如一个列表或者一个字符串。

语法:

for循环的语法格式如下:

for iterating_var in sequence:
   statements(s)

流程图:

实例:

实例

#!/usr/bin/python # -*- coding: UTF-8 -*- for letter in ‘Python‘: # 第一个实例 print ‘当前字母 :‘, letter fruits = [‘banana‘, ‘apple‘, ‘mango‘] for fruit in fruits: # 第二个实例 print ‘当前水果 :‘, fruit print "Good bye!"

尝试一下 ?

以上实例输出结果:

当前字母 : P
当前字母 : y
当前字母 : t
当前字母 : h
当前字母 : o
当前字母 : n
当前水果 : banana
当前水果 : apple
当前水果 : mango
Good bye!


通过序列索引迭代

另外一种执行循环的遍历方式是通过索引,如下实例:

实例

#!/usr/bin/python
# -*- coding: UTF-8 -*-

fruits = [‘banana‘, ‘apple‘, ‘mango‘]
for index in range(len(fruits)):
print ‘当前水果 :‘, fruits[index]

print "Good bye!"

以上实例输出结果:

当前水果 : banana
当前水果 : apple
当前水果 : mango
Good bye!

以上实例我们使用了内置函数 len() 和 range(),函数 len() 返回列表的长度,即元素的个数。 range返回一个序列的数。


循环使用 else 语句

在 python 中,for … else 表示这样的意思,for 中的语句和普通的没有区别,else 中的语句会在循环正常执行完(即 for 不是通过 break 跳出而中断的)的情况下执行,while … else 也是一样。

实例

#!/usr/bin/python
# -*- coding: UTF-8 -*-

for num in range(10,20): # 迭代 10 到 20 之间的数字
for i in range(2,num): # 根据因子迭代
if num%i == 0: # 确定第一个因子
j=num/i # 计算第二个因子
print ‘%d 等于 %d * %d‘ % (num,i,j)
break # 跳出当前循环
else: # 循环的 else 部分
print num, ‘是一个质数‘

尝试一下 ?

以上实例输出结果:

10 等于 2 * 5
11 是一个质数
12 等于 2 * 6
13 是一个质数
14 等于 2 * 7
15 等于 3 * 5
16 等于 2 * 8
17 是一个质数
18 等于 2 * 9
19 是一个质数

更多实例:python 打印菱形、三角形、矩形

Python While 循环语句

Python 循环嵌套

笔记列表

  1. 缘分天注定

    738***[email protected]

    参考地址

    使用内置 enumerate 函数进行遍历:

    for index, item in enumerate(sequence):
        process(index, item)

    实例

    >>> sequence = [12, 34, 34, 23, 45, 76, 89]
    >>> for i, j in enumerate(sequence):
    ...     print i,j
    ...
    0 12
    1 34
    2 34
    3 23
    4 45
    5 76
    6 89

    缘分天注定

    缘分天注定

    738***[email protected]

    参考地址

    9个月前 (02-27)

  2. shenwenwin

    she***[email protected]

    for 使用案例

    使用list.append()模块对质数进行输出。

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
    
    # 输出 2 到 100 简的质数
    prime = []
    for num in range(2,100):  # 迭代 2 到 100 之间的数字
       for i in range(2,num): # 根据因子迭代
          if num%i == 0:      # 确定第一个因子
             break            # 跳出当前循环
       else:                  # 循环的 else 部分
          prime.append(num)
    print prime

    输出结果:

    [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]

    shenwenwin

    shenwenwin

    she***[email protected]

    8个月前 (04-19)

  3. kimiYang

    943***[email protected]

    打印空心等边三角形:

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
    
    # 打印空心等边三角形
    rows = int(raw_input(‘输入行数:‘))
    for i in range(0, rows):
        for k in range(0, 2 * rows - 1):
            if (i != rows - 1) and (k == rows - i - 1 or k == rows + i - 1):
                print " * ",
            elif i == rows - 1:
                if k % 2 == 0:
                    print " * ",
                else:
                    print "   ",
            else:
                print "   ",
        print "\n"

    kimiYang

    kimiYang

    943***[email protected]

    7个月前 (05-05)

  4. feng

    124***[email protected]

    打印1-9三角形阵列:

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
    
    for i in range(1,11):
        for k in range(1,i):
            print k,
            k +=1
        i +=1
        print "\n"

    输出结果:

    1 
    
    1 2 
    
    1 2 3 
    
    1 2 3 4 
    
    1 2 3 4 5 
    
    1 2 3 4 5 6 
    
    1 2 3 4 5 6 7 
    
    1 2 3 4 5 6 7 8 
    
    1 2 3 4 5 6 7 8 9

    feng

    feng

    124***[email protected]

    6个月前 (06-08)

  5. ljm

    131***[email protected]

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
    
    ‘‘‘在python中,for循环后的in跟随一个序列的话,循环每次使用的序列元素,而不是序列
    的下标‘‘‘
    s = ‘qazxswedcvfr‘
    for i in range(0,len(s),2):
        print s[i]
    ‘‘‘enumerate() :
        在每次循环中,可以同时得到下标和元素
        际上,enumerate(),在每次循环中返回的是包含每个元素的定值表,两个元素分别赋值
     index,char‘‘‘
    for (index,char) in enumerate(s):
        print "index=%s ,char=%s" % (index,char)

    ljm

    ljm

    131***[email protected]

    5个月前 (06-27)

  6. 为梦而来

    183***[email protected]

    冒泡排序,来至于高学军:

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
    
    # 冒泡排序# 定义列表 list
    arays = [1,8,2,6,3,9,4]
    for i in range(len(arays)):
        for j in range(i+1):
            if arays[i] < arays[j]:
                # 实现连个变量的互换
                arays[i],arays[j] = arays[j],arays[i]
    print arays

    为梦而来

    为梦而来

    183***[email protected]

    4个月前 (08-02)

  7. forMyPeople

    lwy***[email protected]

    更多实例:python 打印菱形、三角形、矩形的代码感觉,写的有点复杂了,如果让你画圆或者其他图形呢?

    其实运用数学公式,就可以了。比如菱形 |x - w/2| + |y - w/2| = w/2 轻松搞定。

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
    
    width = int(raw_input(‘输入对角线长度: ‘))
    for row in range(width + 1):
        for col in range(width + 1):
            if ((abs(row - width/2) + abs(col - width/2)) == width/2):
                print "*",
            else:
                print " ",
        print " "
时间: 2024-08-08 03:32:31

Python for循环语句的相关文章

Python While 循环语句

Python While循环语句 Python 编程中while语句用于循环执行程序,即在一些条件下,循环执行一些段程序,以处理需要重复处理的相同任务. 执行语句可以是单个语句或语句块. 判断条件可以是任何表达式,任何非零.或非空(null)的值均为true. 当判断条件假false时,循环结束. 实例: #!/usr/bin/python count = 0 while ( count < 9): print 'The count is:', count count = count +1 pr

Python学习-7.Python的循环语句-for语句

Python中循环可以使用for语句来实现 1 list = ['Tom','Lucy','Mary'] 2 for name in list: 3 print(name) 则将会依次输出Tom Lucy Mary 另外Python还支持continue和break关键字,用法与C#相同. 比较有特点的是Python的for语句中支持else关键字 例子: 1 max = 15 2 for i in range(10): 3 if(i==max): 4 break 5 print(i) 6 el

Python的循环语句

Python的循环有两种,一种是for...in循环,第二种循环是while循环,只要条件满足,就不断循环,条件不满足时退出循环 names = ['Michael', 'Bob', 'Tracy'] for name in names: print(name) Michael Bob Tracy #所以for x in ...循环就是把每个元素代入变量x,然后执行缩进块的语句 sum = 0 for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]: sum = sum

python while循环语句

while循环语句 import time  #时 while 条件: 代码块 time.sleep(1)  #延时1秒 ################ import time kaishi =1 flag = true while True: print(kaishi) if kaishi == 10 : flag = False  #(break) #########break 用于跳出循环 kaishi = kaishi + 1 #########continue 用于跳出当前循环 ti

Python条件循环语句

print 'x','y' 相当于 print 'x' print 'y' 输出 x y ------------------------------------------------------------------------------- 从模块导入函数的时候,可以 1. import somemodule                                                                                          

Python 4 循环语句while

while  [条件]:        条件这里满足布尔运算True则无限循环while里面代码. 固定条件的 基本的while循环, 如果if匹配那么 则执行打印登录成功,和break跳出整个循环,否则则执行else输入并重新循环. while 1==1: user = input('用户名:') pwd = input('密码:') if user == "admin" and pwd =="pwd" print("登录成功") break

【Python】循环语句

while循环 当条件成立时,循环体的内容可以一直执行,但是避免死循环,需要有一个跳出循环的条件才行. for循环 遍历任何序列(列表和字符串)中的每一个元素 >>> a = ["China", 'is', 'powerful'] >>> for x in a: ... print(x) ... China is powerful range() 函数 生成一个等差数列(并不是列表). range(4) => range(0, 4) list(

Python学习-8.Python的循环语句-while语句

例子: 1 i = 1 2 while i < 10: 3 print(i) 4 i+=1 5 else: 6 print('finish') 输出1至9和finish 在while语句中同样支持for语句所支持的continue.break和else

python的循环语句等

names = ['Michael', 'Bob', 'Tracy'] for name in names: print name sum = 0 for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]: sum = sum + x print sum sum = 0 n = 99 while n > 0: sum = sum + n n = n - 2 print sum 以上这三种就已经够用了