python中while循环语句的练习
1. 练习一:用户登录
方法一:前面我们使用过for循环实现:
for i in range(3): #0 1 2
name = input('用户名:')
passwd = input('密码:')
if name == 'root' and passwd == 'westos':
print('登陆成功')
# 跳出整个循环,不会再执行后面的内容
break
else:
print('登陆失败')
print('您还剩余%d次机会' %(2-i))
else:
print('登陆次数超过三次,请等待100s后再次尝试登陆')
输出结果:
方法二:while循环
i = 0
while i < 3: # 0 1 2
name = input('用户名:')
passwd = input('密码:')
if name == 'root' and passwd == 'westos':
print('登陆成功')
# 跳出整个循环 不会再执行后面的内容
break
else:
print('登陆失败')
print('您还剩余%d次机会' %(2-i))
i +=1
else:
print('登陆次数超过三次,请等待100s后再试!!!')
输出结果:
2. 练习二:99乘法表
打印99乘法表
第一种:
row = 1
while row <= 9:
col = 1
while col <= row:
print('%d * %d = %d\t' %(row,col,row*col),end='')
col += 1
print('') ##手动换行
row += 1
输出结果:
第二种:
row = 1
while row <= 9:
col = 9
while col >= row:
print('%d * %d = %d\t' % (col, row, col * row), end='')
col -= 1
print('')
row += 1
输出结果:
第三种:
row = 1
while row <= 9:
col = 1
while col < row:
print('\t\t\t',end='')
col += 1
while col >= row and col <= 9:
print('%d * %d = %d\t'%(row,col,row*col),end='')
col += 1
print('')
row += 1
输出结果:
3. 练习三:打印星星
第一种:
row = 1
while row <= 6:
col = 1
while col < row:
print('*', end='')
col += 1
print('')
row += 1
输出结果:
第二种:
row = 1
while row <= 6:
col = 6
while col >= row:
print('*', end='')
col -= 1
print('')
row += 1
输出结果:
第三种:
row = 0
while row <= 6:
col = 0
while col < row:
print('', end='')
col += 1
while col >= row and col < 6:
print('*', end='')
col += 1
print('')
row += 1
输出结果:
第四种:
row = 0
while row <= 6:
col = 0
while col < 6 - row:
col += 1
print(' ', end='')
while col < 6:
print('*', end='')
col += 1
print('')
row += 1
输出结果: