while循环的语法
while 条件:
条件为真时执行以下程序
。。。。。。。。。。
。。。。。。。。。。
#1.定义一个整数变量,记录循环的次数
i = 1
#2.开始循环
while i <= 3:
#希望循环内执行的代码
print('hello python')
#处理计数器
i += 1
#定义死循环
while True:
print('hello python')
while循环求0-100的和:
#1.定义一个整数记录循环的次数
i = 0
#2.定义最终结果的变量
result = 0
#3.开始循环
while i <= 100:
print(i)
#4.每次循环都让result和i这个计数器想加
result += i
#5.处理计数器
i += 1
print('0~100之间的数字求和结果为 %d' %result)
"""
while循环的用户登录系统:
"""
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('登录次数超过三次,请稍后登录')
while嵌套
[kiosk@foundation15 day02]$ /usr/local/python3.6/bin/python3 while输出\*.py
*
**
***
****
*****
[kiosk@foundation15 day02]$ cat while输出\*.py
"""
# _*_coding:utf-8_*_
Name:while输出*.py
Date:1/17/19
Author:westos-liming
Connect:liming.163.com
Desc:
"""
i=1
while i<6:
j=0
while j<i:
print("*",end="") #end""表示输出不换行
j += 1
i += 1
print("") #换行
"""
猜数字游戏:
1.系统随机生成一个1~100的数字;
2.用户共有5次机会猜;
3.如果用户猜测数字大于系统给出的数字,打印"too big"
4.如果用户猜测数字小于系统给出的数字,打印"too small"
5.如果用户猜测的数字等于系统给出的数字,打印"恭喜中奖",
并退出循环
"""
[kiosk@foundation15 day02]$ /usr/local/python3.6/bin/python3 猜数字游戏.py
请输入一个数:50
too big
您还有4次机会
请输入一个数:20
too small
您还有3次机会
请输入一个数:37
too big
您还有2次机会
请输入一个数:31
too big
您还有1次机会
请输入一个数:27
too big
您还有0次机会
[kiosk@foundation15 day02]$ cat 猜数字游戏.py
"""
# _*_coding:utf-8_*_
Name:猜数字游戏.py
Date:1/17/19
Author:westos-liming
Connect:liming.163.com
Desc:
"""
import random
num=random.randint(1,100)
i=5
while i>0:
i -= 1
num_in=int(input("请输入一个数:"))
if num_in > num:
print("too big")
print("您还有%d次机会" %i)
elif num_in < num:
print("too small")
print("您还有%d次机会" %i)
else:
print("恭喜中奖")
break