1 while循环语句格式
1.1 while循环语句格式:
"""
while 条件:
条件满足时,做的事情1
条件满足时,做的事情2
...
"""
#1.定义计数器
i = 0
#2.开始循环
while i < 3:
#循环内需要做的事情
print('hello python')
#处理计数器
i += 1
1.2 while-else循环语句格式:
trycount=0
while trycount<3:
print "login"
trycount+=1
else:
print "bigger than 3"
1.3 定义死循环:
while True:
print('hello python')
2 while循环语句练习
2.1 练习一:0~100的求和
i = 0
sum = 0
while i <= 100:
sum += i
i += 1
print('0~100之间的数字求和结果为: %d' %sum)
2.2 练习二:用户登陆系统(对比for循环语句)
trycount = 0
while trycount < 3:
name = input('用户名: ')
passwd = input('密码: ')
if name == 'root' and passwd == 'westos':
print('登录成功!')
break
else:
print('登录失败')
print('您还剩余%d次机会' %(2-trycount))
trycount += 1
else:
print('失败超过3次,请稍后再试!')
2.3 练习三:while嵌套1
"""
生成如下星形图案
*
**
***
****
*****
"""
row = 1
while row <= 5:
col = 1
while col <= row:
print('*',end='')
col += 1
print('')
row += 1
2.4 练习四:while嵌套2
"""
生成如下星形图案
*****
****
***
**
*
"""
row = 1
while row <= 5:
col = 5
while col >= row:
print('*',end='')
col -= 1
print('')
row += 1
2.5 练习五:while嵌套3
"""
生成九九乘法表
1 * 1 = 1
1 * 2 = 2 2 * 2 = 4
1 * 3 = 3 2 * 3 = 6 3 * 3 = 9
"""
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
2.6 练习六:猜数字
"""
1.随机生成1~100的数字
2.5次机会
3.too big
4.too small
5.恭喜,并退出循环
"""
import random
trycount = 0
computer = random.randint(1,100)
print(computer)
while trycount < 5:
player = int(input('Num: '))
if player > computer:
print('too big')
trycount += 1
elif player < computer:
print('too small')
trycount += 1
else:
print('恭喜')
break
#########################The End##############################