- while 条件():
条件满足时,做的事情1
条件满足时,做的事情2
#1.定义一个变量,记录循环次数
i = 1
#2.开始循环
while i <= 3:
#循环内执行的动作
print('hello python')
#处理计数器
i += 1
2.定义死循环,条件永远为真
while True:
print('hello python')
3.求和:求0-100之间的数字的和
i = 0 #1.定义一个变量记录循环的次数
result = 0 #2.定义结果的变量
while i <= 100: #3.开始循环
result += i #4.每次循环都让result和i这个计数器相加
i += 1 #5.处理计数器
print('和为:%d' %result)
4.用while循环实现用户登录
trycount = 0
while trycount < 3:
name = input('用户名: ')
password = input('密码: ')
if name == 'root' and password == 'westos':
print('登录成功')
break
else:
print('登录失败')
print('您还剩余%d次机会' %(2-trycount))
trycount += 1
else:
print('登录次数超过3次,请稍后再试!')
5.猜数字游戏
1) 系统随机生成一个1~100的数字;
2)用户总共有5次猜数字的机会;
3) 如果用户猜测的数字大于系统给出的数字,打印“too big”;
4) 如果用户猜测的数字小于系统给出的数字,打印"too small";
5) 如果用户猜测的数字等于系统给出的数字,打印"恭喜",并且退出循环;
import random
computer=random.randint(1,100)
for i in range (5):
player=int(input('请输入你猜的数:'))
if player == computer:
print('恭喜!')
exit()
elif (player > computer):
print('too big!')
elif (player < computer):
print('too small!')
#print('你还有%d次机会,请重试!' %(4-i))
else:
print('机会已用完,失败!正确的数为%d' %(computer))
6.输出四种不同形状的星星
row = 5
while row >= 1:
col = 1
while col <= row:
print('*',end='')
col += 1
print('')
row -= 1
*
**
***
****
*****
7.打印9*9乘法表
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