首页 > 编程 > Python > 正文

Python2与python3中 for 循环语句基础与实例分析

2020-02-16 10:46:30
字体:
来源:转载
供稿:网友

下面的代码中python2与python3的print使用区别,大家注意一下。python3需要加()才行。

语法:

for循环的语法格式如下:

for iterating_var in sequence:  statements(s)

流程图:

实例:

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

以上实例输出结果:

当前字母 : j当前字母 : b当前字母 : 5当前字母 : 1当前字母 : .当前字母 : n当前字母 : e当前字母 : t当前水果 : banana当前水果 : apple当前水果 : mango当前水果 : orangeGood 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 * 511 是一个质数12 等于 2 * 613 是一个质数14 等于 2 * 715 等于 3 * 516 等于 2 * 817 是一个质数18 等于 2 * 919 是一个质数

以下是一些实例

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]

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表