【二十二】while和for循环语句

while和for循环语句

while循环

格式: while 判断条件:

​ 执行语句…

a = 1
while a < 4:
print(a) # 1 2 3
a += 1

while True

  • 无限循环(俗称:死循环),配合控制语句去限制循环次数
a = 0
while True:
	print("hello")
	a += 1
	if a == 3:
	break

while … else

  • while 循环语句结束后将会执行相对应的else语句,不过如果使用break跳出循环,那么else语句也不会执行
count = 0

while count < 5:
	print(count, "小于5")
	count = count + 1
else:
	print(count, "大于或等于 5")

    
count = 0

while count < 5:
	print(count, "小于5")
	count = count + 1
    
print(count, "大于或等于 5")


count = 0

while True:
	print(count, "小于5")
	count = count + 1
	if count >= 5:
		break
else:
    
	print(count, "大于或等于 5")
    
    
count = 0

while True:
	print(count, "小于5")
	count = count + 1
	if count >= 5:
		break
        
print(count, "大于或等于 5")

while 循环嵌套

# 实现九九乘法表
right = 1
while right <= 9:
	left = 1
	while left <= right:
		print(f"{left}x{right}={left*right}", end="\t")
		left += 1
	print()
	right += 1

for 循环

for 变量 in 可迭代对象:

​ 执行语句…

str1 = "123ab"
lis1 = [1, 2, 3, "a", "b"]
tup1 = (1, 2, 3, "a", "b")
dic1 = {"one": 1, "two": 2}
set1 = {3, 2, 4, "a"}

for i in str1:
	print(i)
for i in lis1:
	print(i)
for i in tup1:
	print(i)
for i in dic1:
	print(i)
for i in set1:
	print(i)

for … in … else

*与while else 结构类似,for循环语句结束后将会执行相对应的else语句,不过如果使用break跳出循环,那么else语句也不会执行

for i in [1, 2, 3, 4]:
	print(i)
	if i > 2:
		break
else:
	print(5)
for i in [1, 2, 3, 4]:
	print(i)
	if i > 2:
		break
print(5)

for 循环嵌套

# 实现九九乘法表
for right in range(1, 10):
	for left in range(1, right+1):
		print(f"{left}x{right}={left*right}", end="\t")
	print()
    

range和enumerate

range(stop) / range(start, stop[, step])

  • 返回一个按步骤生成的从start(包括)到stop(不包括)的整数序列,它是不可变的序列,是可迭代对象
  • start:计数从 start 开始,默认是从 0 开始 stop:计数到
  • stop 结束,但不包括 stop
  • step:步长,默认为1
  • range 类型相比常规 list 或 tuple 的优势在于一个 range 对象总是占用 固定数量的(较小)内存,不论其所表示的范围有多大(因为它只保 存了 start, stop 和 step 值)
print(list(range(4))) # [0, 1, 2, 3]
print(list(range(1, 5))) # [1, 2, 3, 4]
print(list(range(1, 8, 2))) # [1, 3, 5, 7]
print(list(range(8, 1, -2))) # [8, 6, 4, 2]

enumerate(iterable, start=0)

  • 返回一个enumerate对象(迭代器)。迭代它会得到一个个的元组, 每个元组是索引(从start开始,默认为 0)和索引对应iterable的值组成的
seasons = ['Spring', 'Summer', 'Fall', 'Winter']
object1 = enumerate(seasons) # <enumerate object at0x000002A89E67E6C0>
print(list(object1)) # [(0, 'Spring'), (1, 'Summer'),(2, 'Fall'), (3, 'Winter')]

object2 = enumerate(seasons, start=1) # 设置开始迭代的索引
print(list(object2)) # [(1, 'Spring'), (2, 'Summer'),(3, 'Fall'), (4, 'Winter')]


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值