- while 条件():
条件满足时,做的事情1
条件满足时,做的事情2
#1.定义一个变量,记录循环次数
i = 1
#2.开始循环
while i <= 3:
#循环内执行的动作
print('hello python')
#处理计数器
i += 1
- while死循环
while True:
print('hello python')
- 练习:
- 1.计算0~100之间的数字求和结果
i = 0
result = 0
while i <= 100:
result += i
i += 1
print('和为:%d' %result)
2.用while循环打出四种星星形状
第一种
*
**
***
****
*****
row = 5
while row >= 1:
col = 1
while col <= row:
print('*',end='')
col += 1
print('')
row -= 1
第二种
*
**
***
****
*****
row = 1
while row <= 9:
col = 1
while col <= row:
print('%d * %d = %d\t' %(row,col,col * row),end='')
col += 1
print('')
row += 1
第三种
*****
****
***
**
*
row = 5
while row>= 0:
col = 1
while col <= row:
print("*",end='')
col += 1
print()
row -= 1
第四种
*****
****
***
**
*
row= 1
while row <= 5:
col = 1
while col < row:
print(" ",end='')
col += 1
while col >= row and col <= 5:
print("*",end='')
col += 1
print()
row += 1
3.猜数字游戏
- 系统随机生成一个1~100的数字;
- 用户总共有5次猜数字的机会;
- 如果用户猜测的数字大于系统给出的数字,打印“too big”;
- 如果用户猜测的数字小于系统给出的数字,打印"too small";
- 如果用户猜测的数字等于系统给出的数字,打印"恭喜",并且退出循环;
“”"
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
版权声明:本文为qq_44236589原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。