while循环
1. 一个while
语句会一遍又一遍的重复一段代码,只要某些条件是正确的。下面是举一些例子:
eg1 : 求1+ 2+ 3+……+100的和:
sum = 0
i = 1
while i <= 100 :
sum += i
i += 1
print(sum)
只要i <= 100 这个条件一直成立,程序就会一遍一遍执行,直到条件不成立。
2. while循环应该应用更多样,因为它可以进行判断,同样它的使用也会复杂点!
eg2 :
i = 1
while i <= 3:
username = input('请输入用户名:')
userpasswd = input('请输入密码:')
if username == 'root' and userpasswd == 'westos':
print('登陆成功!')
break
else:
print('登陆失败!')
print('您已经登陆%d次,还有%d次机会!' %(i,3-i))
i += 1
else:
print('三次机会已经使用完,请100s后重试!')
3. while死循环:
语法结构如下:
while True:
循环执行的动作
while死循环一般用于某些重复次数不确定的、且变动幅度较大的场景。
eg :
4.while嵌套:
我们通过几个例子来体会while的嵌套:
(1) while中嵌套for循环 实现 正着 和 倒着打印三角*形状:
row = 1
column = 1
while row <= 5:
for column in range(1,column+1):
print('*',end='')
print(' ')
column += 1
row += 1
运行结果:
row = 1
column = 5
while row <= 5:
for column in range(1,column+1):
print('*',end='')
print(' ')
column -= 1
row += 1
运行结果:
(2)while中嵌套while循环 实现 正着 和 倒着打印三角*形状
row = 1
column = 1
i = 1
while row <= 5:
while i <= column:
print('*',end='')
i += 1
print('')
i = 1
column += 1
row += 1
运行结果:
row = 1
column = 5
i = 1
while row <= 5:
while i <= column:
print('*',end='')
i += 1
print('')
i = 1
column -= 1
row += 1
运行结果:
(3) 附加题:
line = 5
for i in range(line):
j = 0
while j < i :
print(' ',end='')
j += 1
j = 0
k = 0
while k < line:
print('*',end='')
k += 1
k = 0
print(' ')
line -= 1
运行结果:
line = 5
for i in range(1,line+1):
j = 1
while j < line:
print(' ', end='')
j += 1
k = 0
while k < i:
print('*', end='')
k += 1
print(' ')
line -= 1
运行结果:
(4)用程序实现打印出九九乘法表:
方法一:
row = 1
while row <= 9:
column = 1
while column <= row :
print ('%d*%d=%d ' %(row,column,row*column),end='')
column += 1
print(' ')
row += 1
方法二:
row = 1
column = 1
while row <= 9:
i = 1
while i <= column:
print('%d*%d=%d\t' %(row,i,row*i),end='')
i += 1
print('')
column += 1
row += 1
5. 几个特殊字符:
\t: 在控制台输出值表符,协助我们在输出文本时,在垂直方向保持对齐
\n: 在控制台输出换行符
\: 转译字符