Python学习笔记 Day2

循环的实现

for循环

基本语法

在python中,for循环的功能十分强大,使用起来有些类似C++中的auto类型有些类似

for iterator in sequence #基本形式,iterator的类型和sequence的元素类型相同、

for i in "Hello world":
	print(i)  #输出字符串中的每一个字符
    
prime=[2,3,5,7,11,13]
for i in prime:
	print(i)  #输出数组中的每一个元素
for i in range(len(prime)):
	print(prime[i]) #另一种使用方法

for i in range(1,5):
	print(i) #输出[1,5)之间的数
    
for i in range(1,10,2):
	print(i) #以2为间隔,输出[1,10)之间的数

可以注意到,在for循环的使用中,range是一个十分重要的组成部分,以下是range的使用方法

range(x) #只有一个参数时表示[0,x)之间的整数,但是要注意,此时的i不会被初始化为0

range(a,b) #表示从[a,b)的所有整数

range(a,b,I)#表示以I为间隔,输出[a,b)之间的数

for循环中的else语句

与for同等级的else中,只有在for不是被break掉时才会执行else中的内容,例如以下代码

#coding=UTF8
prime=[2,3,5,7,11,13]
for i in range(14):
	for j in range(0,len(prime)):
		if prime[j]==i:
			print(i,"is in the sequence")
			break
	else:
		print(i,"is not in the sequence")

得到的预期输出为:

0 is not in the sequence
1 is not in the sequence
2 is in the sequence
3 is in the sequence
4 is not in the sequence
5 is in the sequence
6 is not in the sequence
7 is in the sequence
8 is not in the sequence
9 is not in the sequence
10 is not in the sequence
11 is in the sequence
12 is not in the sequence
13 is in the sequence

可以看出只有在正常结束循环时,才会执行else中的语句

while循环

基本语法

这是一个简单的while使用样例,过于简单不做讲解:

#coding=UTF8
i=0
while i<5:
	print(i)
	i+=1

如果while中仅有一条语句,则可以和while写在一行

while循环中的else语句

只有在while正常执行完时才会执行else中的语句,例如以下代码

#coding=UTF8
i=0
while i<5:
	print(i)
	i+=1
    '''
	if i==3:
		break
	'''
else:
	print("Running")

该程序运行时,将会输出Running,如果删除注释符,则当\(i=3\)时程序将会break,不会触发else中的内容

posted @ 2021-02-03 23:12  Fang_Hao  阅读(54)  评论(0编辑  收藏  举报