在Python的while循环中使用else以及循环嵌套的用法

yipeiwu_com5年前Python基础

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

#!/usr/bin/python

count = 0
while count < 5:
  print count, " is less than 5"
  count = count + 1
else:
  print count, " is not less than 5"

以上实例输出结果为:

0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is not less than 5

简单语句组
类似if语句的语法,如果你的while循环体中只有一条语句,你可以将该语句与while写在同一行中, 如下所示:

#!/usr/bin/python

flag = 1

while (flag): print 'Given flag is really true!'

print "Good bye!"

注意:以上的无限循环你可以使用 CTRL+C 来中断循环。

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

for iterating_var in sequence:
 for iterating_var in sequence:
  statements(s)
 statements(s)

Python while 循环嵌套语法:

while expression:
 while expression:
  statement(s)
 statement(s)


你可以在循环体内嵌入其他的循环体,如在while循环中可以嵌入for循环, 反之,你可以在for循环中嵌入while循环。
实例:
以下实例使用了嵌套循环输出2~100之间的素数:#!/usr/bin/python

# -*- coding: UTF-8 -*-

i = 2
while(i < 100):
j = 2
while(j <= (i/j)):
if not(i%j): break
j = j + 1
if (j > i/j) : print i, " 是素数"
i = i + 1


print "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!

相关文章

使用python实现哈希表、字典、集合操作

使用python实现哈希表、字典、集合操作

哈希表 哈希表(Hash Table, 又称为散列表),是一种线性表的存储结构。哈希表由一个直接寻址表和一个哈希函数组成。哈希函数h(k)将元素关键字k作为自变量,返回元素的存储下标。...

对python requests的content和text方法的区别详解

问题: 一直在想requests的content和text属性的区别,从print 结果来看是没有任何区别的 看下源码: @property def text(self):...

Python读取txt文件数据的方法(用于接口自动化参数化数据)

Python读取txt文件数据的方法(用于接口自动化参数化数据)

小试牛刀: 1.需要python如何读取文件 2.需要python操作list 3.需要使用split()对字符串进行分割 代码运行截图 : 代码(copy) #encoding=...

python中类的一些方法分析

本文实例分析了python中类的一些方法,分享给大家供大家参考。具体分析如下: 先来看看下面这段代码: class Super: def delegate(self):...

pytorch中如何使用DataLoader对数据集进行批处理的方法

pytorch中如何使用DataLoader对数据集进行批处理的方法

最近搞了搞minist手写数据集的神经网络搭建,一个数据集里面很多个数据,不能一次喂入,所以需要分成一小块一小块喂入搭建好的网络。 pytorch中有很方便的dataloader函数来方...