python下while的用法(0~100之间的数字求和,while实现用户登录需求)

一:while的用法

“”"
while 条件():
条件满足时,做的事情1
条件满足时,做的事情2

“”"

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

在这里插入图片描述
while死循环:

#定义死循环,会一直执行下去
while True:
    print('hello python')

在这里插入图片描述

实例1: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)

在这里插入图片描述
实例2: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/bmengmeng/article/details/94002589