pyhon 中 for 循环可以遍历任何序列的项目,如一个字典或者一个字符.

for 循环格式一般如下:

for <variable-变量> in <sequence-序列>:
<statement>
else:
<statement>

实例:

>>>languages = ["C", "C++", "Perl", "Python"]
>>> for x in languages:
... print (x)
...
C
C++
Perl
Python

以下for实例中使用了break语句,break用于跳出当前循环体:

sites = ["Baidu", "Google","Zhihu","Taobao"]
for site in sites:
if site == "Zhihu":
print("666!")
break
print("循环数据 " + site)
else:
print("没有循环数据!")
print("完成循环!")

执行后,在循环到 "Runoob"时会跳出循环体:

循环数据 Baidu
循环数据 Google
666!
完成循环!

range() 函数


如果需要遍历数字序列,可以使用内置range()函数;它会生成数列,例如:

>>>for i in range(5):
... print(i)
...
0
1
2
3
4

也可以使用range()指定区间的值(遍历时range序列顾头不顾尾):

>>>for i in range(5,9) :
print(i) 5
6
7
8
>>>

也可以使range指定数字开始并指定不同的增量(也可以是负数,即‘步长’):

>>>for i in range(0, 10, 3) :
print(i) 0
3
6
9
>>>

负数加步长:

>>>for i in range(-10, -100, -30) :
print(i) -10
-40
-70
>>>

同时可以结合range()和len()函数遍历一个序列的索引,如下所示:

>>>a = ['Google', 'Baidu', 'Zhihu', 'Taobao', 'QQ']
>>> for i in range(len(a)):
... print(i, a[i])
...
0 Google
1 Baidu
2 Zhihu
3 Taobao
4 QQ
>>>

使用range()函数创建一个列表:

>>>list(range(5))
[0, 1, 2, 3, 4]
>>>

break和continue语句及循环中的else子句:

break语句可以跳出for和while循环体;如果你从for或者while循环中终止,任何对应的else块将不执行。例如:

for letter in 'Runoob':     # 第一个实例
if letter == 'b':
break
print ('当前字母为 :', letter) var = 10 # 第二个实例
while var > 0:
print ('当前变量值为 :', var)
var = var -1
if var == 5:
break print ("Good bye!")

执行结果:

当前字母为 : R
当前字母为 : u
当前字母为 : n
当前字母为 : o
当前字母为 : o
当期变量值为 : 10
当期变量值为 : 9
当期变量值为 : 8
当期变量值为 : 7
当期变量值为 : 6
Good bye!

continue语句用来告诉python跳过当前循环快中的剩余语句,然后继续进行下一轮循环。

实例:

for letter in 'Runoob':     # 第一个实例
if letter == 'o': # 字母为 o 时跳过输出
continue
print ('当前字母 :', letter) var = 10 # 第二个实例
while var > 0:
var = var -1
if var == 5: # 变量为 5 时跳过输出
continue
print ('当前变量值 :', var)
print ("Good bye!")

结果:

当前字母 : R
当前字母 : u
当前字母 : n
当前字母 : b
当前变量值 : 9
当前变量值 : 8
当前变量值 : 7
当前变量值 : 6
当前变量值 : 4
当前变量值 : 3
当前变量值 : 2
当前变量值 : 1
当前变量值 : 0
Good bye!

循环语句可以有 else 子句,它在穷尽列表(以for循环)或条件变为 false (以while循环)导致循环终止时被执行,但循环被break终止时不执行。

如下实例用于查询质数的循环例子:

for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print(n, '等于', x, '*', n//x)
break
else:
# 循环中没有找到元素
print(n, ' 是质数')

结果:

2  是质数
3 是质数
4 等于 2 * 2
5 是质数
6 等于 2 * 3
7 是质数
8 等于 2 * 4
9 等于 3 * 3

pass 语句

pass是空语句,是为了保持程序结构的完整性,不做任何事情,一般用做占位语句,如下实例:

>>>while True:
... pass # 等待键盘中断 (Ctrl+C)

以下实例在字母为 o 时 执行 pass 语句块:

for letter in 'Runoob':
if letter == 'o':
pass
print ('执行 pass 块')
print ('当前字母 :', letter) print ("Good bye!")

结果:

当前字母 : R
当前字母 : u
当前字母 : n
执行 pass 块
当前字母 : o
执行 pass 块
当前字母 : o
当前字母 : b
Good bye!

for and range()的更多相关文章

  1. SQL Server 合并复制遇到identity range check报错的解决

        最近帮一个客户搭建跨洋的合并复制,由于数据库非常大,跨洋网络条件不稳定,因此只能通过备份初始化,在初始化完成后向海外订阅端插入数据时发现报出如下错误: Msg 548, Level 16, S ...

  2. Java 位运算2-LeetCode 201 Bitwise AND of Numbers Range

    在Java位运算总结-leetcode题目博文中总结了Java提供的按位运算操作符,今天又碰到LeetCode中一道按位操作的题目 Given a range [m, n] where 0 <= ...

  3. [LeetCode] Range Addition 范围相加

    Assume you have an array of length n initialized with all 0's and are given k update operations. Eac ...

  4. [LeetCode] Count of Range Sum 区间和计数

    Given an integer array nums, return the number of range sums that lie in [lower, upper] inclusive.Ra ...

  5. [LeetCode] Range Sum Query 2D - Mutable 二维区域和检索 - 可变

    Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper lef ...

  6. [LeetCode] Range Sum Query - Mutable 区域和检索 - 可变

    Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive ...

  7. [LeetCode] Range Sum Query 2D - Immutable 二维区域和检索 - 不可变

    Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper lef ...

  8. [LeetCode] Range Sum Query - Immutable 区域和检索 - 不可变

    Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive ...

  9. [LeetCode] Bitwise AND of Numbers Range 数字范围位相与

    Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers ...

  10. C++11中自定义range

    python中的range功能非常好用 for i in range(100): print(i) 现在利用C++11的基于范围的for循环特性实现C++中的range功能 class range { ...

随机推荐

  1. 小马哥课堂-统计学-t分布

    T distribution 定义 在概率论和统计学中,学生t-分布(t-distribution),可简称为t分布,用于根据小样本来估计 呈正态分布且方差未知的总体的均值.如果总体方差已知(例如在样 ...

  2. PHP学习笔记(14)班级和学生管理---学生

    两个文件夹,一个班级cls,一个学生stu. 两个表,一个班级cls,一个学生stu. 每个文件夹里有7个php文件:主界面stu.php-------增add.php,insert.php----- ...

  3. Oracle 错误 maximum number of processes(150) exceeded 解决办法

    网上很多同行应该都遇到过这个问题,百度一搜 千篇一律的处理办法,就是加大进程数. 但是我这边情况不一样,因为我的Oracle 11g是早上刚装的,跟本没人用,我用PLSQL链接照样说不能链接. 我就在 ...

  4. Angular4中的依赖注入

    在Angular中使用依赖注入,可以帮助我们实现松耦合,可以说只有在组件中使用依赖注入才能真正 的实现可重用的组件. 如果我们有个服务product.service.ts,其中export了一个Pro ...

  5. Switch选择语句能否作用在String【字符串】上,也就是能否这么写:Switch(一个字符串变量)?

    Switch选择语句能否作用在String[字符串]上,也就是能否这么写:Switch(一个字符串变量)? 解答:不可以,只能处理int,byte,short,char,(其实是只能处理int,其它三 ...

  6. SQLite 连接两个字符串

    SQLite中,连接字符串不是使用+,而是使用|| 示例: SELECT 'I''M '||'Chinese.' 将输出 I'M Chinese. 特别说明:1. SELECT 'I''M '+'Ch ...

  7. 嵌入式驱动开发之dsp fpga通信接口---spi串行外围接口、emif sram接口

    -----------------------------------------author:pkf ------------------------------------------------ ...

  8. ACM/ICPC Moscow Prefinal 2019 趣题记录

    ### Day1: ### **Problem C:** 设$k_i​$为$[A, B]​$中二进制第$i​$位是1的数的个数. 给出$k_0 \cdots k_{63}​$, 求出$[A, B]​$ ...

  9. 【翻译自mos文章】使用asm来部署 超大数据库(10TB到PB 范围)--针对oracle 10G

    使用asm来部署 超大数据库(10TB到PB 范围) 參考原文: Deployment of very large databases (10TB to PB range) with Automati ...

  10. Deep Learning阅读资料

    入门基础阅读:http://www.cnblogs.com/avril/archive/2013/02/08/2909344.html 书籍推荐:http://blog.chinaunix.net/u ...