Python for while循环
一. while 循环
while_stmt ::= "while" assignment_expression ":" suite
["else" ":" suite]
while 条件:
条件满足时,执行语句
1. 1~100求和运算
i = 0
r = 0
while i <= 100:
r += i
i += 1
print('1+2+3+...+100 = %d' % r) # 5050,计算1~100求和
我们可以通过设置条件表达式永远不为 false 来实现无限循环,实例如下:
2. while 无限循环
while True:
print("hello,21yi.com") # CTRL+C退出循环
# 无限循环实现简单的密码验证
while True:
password = input('请输入您的密码:')
if "21yi.com" == password:
print('密码正确')
break
else:
print('密码错误')
continue
使用 CTRL+C 来退出当前的无限循环。
无限循环在服务器上客户端的实时请求非常有用。
3. while 嵌套
类似if语句,while也支持嵌套,如嵌套实现9x9乘法表:
level = 1
while level <= 9:
init = 1
while init <= level:
print('%d x %d = %d\t' % (level, init, init * level), end='')
init += 1
print('\r')
level += 1
# 1 x 1 = 1
# 2 x 1 = 2 2 x 2 = 4
# 3 x 1 = 3 3 x 2 = 6 3 x 3 = 9
# 4 x 1 = 4 4 x 2 = 8 4 x 3 = 12 4 x 4 = 16
# 5 x 1 = 5 5 x 2 = 10 5 x 3 = 15 5 x 4 = 20 5 x 5 = 25
# 6 x 1 = 6 6 x 2 = 12 6 x 3 = 18 6 x 4 = 24 6 x 5 = 30 6 x 6 = 36
# 7 x 1 = 7 7 x 2 = 14 7 x 3 = 21 7 x 4 = 28 7 x 5 = 35 7 x 6 = 42 7 x 7 = 49
# 8 x 1 = 8 8 x 2 = 16 8 x 3 = 24 8 x 4 = 32 8 x 5 = 40 8 x 6 = 48 8 x 7 = 56 8 x 8 = 64
# 9 x 1 = 9 9 x 2 = 18 9 x 3 = 27 9 x 4 = 36 9 x 5 = 45 9 x 6 = 54 9 x 7 = 63 9 x 8 = 72 9 x 9 = 81
二. for 循环语句
Python for循环可以遍历如(字符串、元组、列表)等其他可遍历的对象
for_stmt ::= "for" target_list "in" expression_list ":" suite
["else" ":" suite]
# 数字List
for i in range(1, 6): # [1,2,3,4,5]
print(i) # 1 2 3 4 5
# 字符串
for i in "21yi.com":
print(i)
三. continue语句
在语句块执行过程中终止当前循环,跳出本次循环,执行下一次循环,while和for语句都适用。如下:
for i in "21yi.com":
if i == ".":
continue # 跳出本次循环,执行下一次
else:
print(i)
四. pass语句
pass是空语句,是为了保持程序结构的完整性,选择性使用
# 输出 Python 的每个字母
for i in '21yi.com':
if i == '.':
pass
print('Pass语句')
print(i)
print('end')