python基础—while循环

while循环语法:

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

while死循环:

while True:
    print('hello world')

练习1:
分别求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)

完整代码如下:

"""
# _*_coding:utf-8_*_
Name:jishuhe.py
Date:1/14/19
Author:westos-sql
Connect:[email protected]
Desc:...
"""
i  = 0
result = 0
while i <= 100:
    result += i
    res = 5050 - result
    i += 2
print('oshuhe is: %d' %result)
print('jishuhe is: %d' %res )

python基础—while循环

执行结果:
python基础—while循环

练习2:打印9*9乘法表
代码如下:

"""
# _*_coding:utf-8_*_
Name:multi.py
Date:1/14/19
Author:westos-sql
Connect:[email protected]
Desc:...
"""
i = 1
while i <= 9:
    j = 1
    while j <= i:
        print('%d * %d = %2d  ' %(i,j,i*j),end='')
        j += 1
    i += 1
    print('')

python基础—while循环

打印结果:
python基础—while循环