Python编程-while循环

  • while循环格式:
    在这里插入图片描述
  • 练习1:输出三次hello python
    1.程序内容为:
#1.定义一个整数变量,记录循环的次数
i = 1
#2.开始循环
while i <= 3:
#希望循环内执行的代码
    print('hello python')
#处理计数器
    i += 1
  1. 运行该程序
    在这里插入图片描述
    在这里插入图片描述
  • 练习2:求1~100所有奇,偶数之和
    1.程序内容为:
i=0
a=0
b=0
while i <= 100:
    if i % 2 ==0:
        a = a + i
    else:
        b = b + i
    i += 1
print('所有偶数之和为%d' %(a))
print('所有奇数之和为%d' %(b))

2.运行该程序:
在这里插入图片描述 在这里插入图片描述

  • 练习3:求0~4所有数之和
    1.程序内容为:
#1.定义一个整数记录循环的次数
i = 0

#2.定义最终结果的变量
result = 0

#3.开始循环
while i <= 4:
    print(i)
    #4.每次循环都让result和i这个计数器相加
    result += i
    #5.处理计数器
    i += 1
print('0~4之间的数字求和结果为 %d' %result)

2.运行该程序:
在这里插入图片描述
在这里插入图片描述

  • 练习4:
    1.用户登陆需求:
    在这里插入图片描述
    2.程序内容为:
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('登录次数超过三次,请稍后登录')

3.执行该程序:
在这里插入图片描述
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/y_yang666/article/details/86527817