3-循环语句:while_for_break_continue【python基础】

3-循环语句:while_for_break_continue

1、while循环

count = 0
while count <=9:
	print(count)
	count += 1  # count = count + 1

输出:
在这里插入图片描述

  • 若是不想每打印一个数就回车:
result = ''
count = 0
while count <=9:
	result += str(count) + ' '
	count += 1  # count = count + 1
print(result)

输出:
在这里插入图片描述

或者:

count = 0
while count <=9:
	print(count,end=' ')
	count += 1  # count = count + 1
print('Done')  # 说明9后面还有一个空格
# print() 默认是有回车
print('Done')

注意:

count = 0
while count <= 9:
	print(count, end=' ')
	count += 1
else:    # 前面的while都执行完后,会执行else的内容
	print('end')
#else的两行就相当于这一行语句:
#print('end')

2、for循环:

for循环用于遍历一个集合。每次循环,会从集合中取得一个元素,并执行一次代码块,直至集合中所有的元素都获取,for循环才结束。

for循环的语法格式如下:

for 变量 in 可迭代对象:
	循环体语句

python可以遍历的对象有 序列(字符串、列表、元组)、字典、迭代器对象(iterator)、生成器函数文件对象。

names = ['Tom','Mary','Jack']   # []:列表
for name in names:
	print(name)

扩展:

print(range(4) ) #返回 range(0,4) -- 是一个对象 -- pyhton2.x返回的是[0,1,2,3]
list(range(4)) # [0, 1, 2, 3]  # 默认step为1

如:

names = ['Tom','Mary','Jack']   # []:列表--是有序的集合
for i in range(len(names)):   # len:求names集合元素个数
	print(names[i])
else: # 前面的while都执行完后,会执行else的内容
	print('end')

返回结果:
Tom
Mary
Jack
end

和上述的打印结果相同,但原理不同。

3、循环嵌套

应用举例:

  • 求最优解 – 进行迭代 – 梯度下降。
for g in gpus:   # 分多个gpu上
	for e in epoches:   # 迭代轮次
		for b in batches:   # 分批次

例子:打印9x9乘法表:

  • while循环
j = 1
while j <= 9:	
	i = 1
	while i <=j:
		print("%d*%d=%d"%(i, j, i*j),end='\t')  # 格式化输出;'\t'制表符-Tab键
		i += 1
	print()   # 换行
	j += 1

在这里插入图片描述

range】:

# range的step默认为1
print(list(range(1,10)))   # [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(list(range(1,10,2)))   # [1, 3, 5, 7, 9]
  • for循环:
i = 1
j = 1
for j in range(1,10):   # 1~9,左闭右开;range的step默认为1
	for i in range(1,j+1):
		print("%d*%d=%d"%(i,j,i*j),end = '\t')
		i +=1
	print()
	j += 1

4、break-continue

  • break语句可以用于while和for循环,用来结束整个循环。当有嵌套循环时,break语句只能跳出最近一层循环
  • continue用于结束本次循环,继续下一次。多个循环嵌套时,continue也是应用于最近的一层循环。而break语句用来彻底退出循环。
for i in range(1,10):
	if i % 2 == 0:  #偶数
		continue
	print(i)

在这里插入图片描述

names = ['Tom','Mary','Lily','Jack']
for i in range(len(names)):   # i 最开始 0 
	if i >= 2:
		break
	print(names[i])

返回值:
Tom
Mary

  • 嵌套的循环
for i in range(3):
	for i in range(1,10):
		if i % 2 == 0:  #偶数
			continue  # 回到最近的一层for循环
		print(i)
  • 输出:1 3 5 7 9 循环3次
names = ['Tom','Mary','Lily','Jack']
for i in range(3):
	for i in range(len(names)):   # i 最开始 0 
		if i >= 2:
			break
		print(names[i])

Tom
Mary
循环输出3次

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

て°倾寒し

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值