while 和 for 相当把里面的代码执行了 n 次
1. while 循环 -> 无序循环
- 基本用法
index = 1
while index <= 20:
print(index)
index += 1
- break 跳出循环
index = 1
while index <= 100:
print(index)
index += 1
if index == 51:
break
- continue 跳出本次循环
index = 0
while index <= 100:
index += 1
if 20 < index < 90:
continue
print(index)
- pass -> pass是空语句,是为了保持程序结构的完整性。pass 不做任何事情,一般用做占位语句。
index = 0
while index <= 100:
index += 1
if 20 < index < 90:
pass
else:
print(index)
- while else -> else while 循环结束后执行 当 while 循环被 break 打断,就不会执行 else
username = 'Kevin'
password = '123'
index = 1
while index <= 3:
input_name = input('请输入用户名:')
input_pass = input('请输入密码:')
if input_name == username and input_pass == password:
print('登录成功')
break
else:
index += 1
print('登录失败')
else:
print('登录次数已经超过了三次')
1.1 while 循环练习
- 使用while循环输入 1 2 3 4 5 6 8 9 10
index = 0
while index < 10:
index += 1
if index > 6 and index < 8:
continue
print(index)
- 输出 1-100 所有数的和
index = 1
count = 1
while index < 100:
index += 1
count += index
print(count)
- 输出 1-100 的所有奇数
index = 0
while index < 100:
index += 1
if index % 2 == 0:
continue
print(index)
- 输出 1-100 的所有偶数
index = 0
while index < 100:
index += 1
if index % 2 == 1:
continue
print(index)
- 求1-2+3-4+5 ... 99的所有数的和
index = 1
count = 1
while index < 100:
index += 1
if index % 2 == 0:
count -= index
elif index % 2 == 1:
count += index
print(count)
- 用户登录(三次机会)
username = 'Kevin'
password = '123'
index = 1
while index <= 3:
input_name = input('请输入用户名:')
input_pass = input('请输入密码:')
if input_name == username and input_pass == password:
print('登录成功')
break
else:
index += 1
print('登录失败')
else:
print('登录次数已经超过了三次')
2. for 循环 -> 有序循环
- 当循环字符串的时候字符串会先存到 for 循环当中,当字符串被修改了也不会影响for循环
- 当循环列表的时候 for 循环会引用列表进行循环,当列表被修改会影响for循环
arr = [1, 2, 3, 4]
for i in arr:
print(i)
- for循环的分别赋值
tuple_list = ([1, 2], [3, 4], [5, 6])
for i1, i2 in tuple_list:
print(i1, i2) # 1 2 ……
- for else -> else for 循环结束后执行 当 for 循环被 break 打断,就不会执行 else,和 while else 是一样的
for i in range(10):
print(i)
else:
print('循环结束了')
for i in range(10):
if i == 5:
break
print(i)
else:
print('循环结束了')
- enumerate() -> 枚举 -> 对一个可遍历的数据对象(如列表、元组或字符串),enumerate会将该数据对象组合为一个索引序列,同时列出数据和数据的下标
arr = ['一', '二', '三']
for i in enumerate(arr):
print(i) # (0, '一')
for i, k in enumerate(arr):
print(i, k) # 0 一
- for循环的嵌套使用
- 注意: for循环的嵌套使用里面的for变量不要和外面的for变量重名,不然在循环的过程中里面的for变量会覆盖前面的for变量的值
a = 0
for i in range(10):
for j in range(10):
for k in range(10):
a = a + k + j + i
2.1 for 循环练习
- 打印输出连续数字出现的次数
info = input('>>>') # 123adad1addsd123dad1
for v in info:
if v.isalpha():
info = info.replace(v, ' ')
print(info) # 123 1 123 1
info = info.split()
print(info) # ['123', '1', '123', '1']
print(len(info)) # 4
← 循环删除列表或字典中的值 报错的查看技巧 →