python[while循环]

while 条件():
条件满足时,做的事情1
条件满足时,做的事情2
#1.定义一个整数变量,记录循环的次数
i = 1
#2.开始循环
while i <= 3:
#希望循环内执行的代码
print(‘hello python’)
#处理计数器
i += 1

while死循环

定义死循环
while True:
print(‘hello python’)

练习例子

用while循环来算1到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循环来解决用户登陆问题

#for i in range(3):     和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('登录次数超过三次,请稍后登录')

猜你喜欢

转载自blog.csdn.net/weixin_43407305/article/details/86521949