while循环的目的:计数时一般会用到while循环

1、打印5次hello

i=0
while i<5:
    i+=1
    print("hello")

2、求1-100之间的和

i = 0
result = 0
while i <= 100:
    # print(i)
    result += i
    i += 1
    # print(i)
print(result)

3、求1-100之间的奇数和

i = 0
while i < 100:
    i = i+1
    if i % 2 != 0:
        print(i)

4、输出1-2+3-4+5…99所有数的和

i = 0
result = 0
while i < 99:
    i += 1
    if i % 2 == 0:
        result -= i
    else:
        result += i
print(result)

5、用户登录有3次机会,有用户名和密码

i = 1
while i <= 3:
    i += 1
    name = str(input("请输入用户名:"))
    password = int(input("请输入密码:"))
    if name == "root"and password == 123456:
        print("用户名和密码正确")
        break
    else:
        print("用户名或者密码错误,您的机会还剩%d次" % (4-i))

6、while调试正三角形

i = 1
while i <= 9:
    #2.1打印列数
    j = 0
    while j < i:
        j = j+1
        #把三角形换成(*)(9*9=81,把行和列用相应内容替代就好)
        print("*", end="")
        # print("%d*%d=%d" % (j, i, i*j), end="\t")
    i = i + 1
    print("")

6、while调试99乘法表

i = 1
while i <= 9:
    #2.1打印列数
    j = 0
    while j < i:
        j = j+1
        #把三角形换成(*)(9*9=81,把行和列用相应内容替代就好)
        # print("*", end="")
        print("%d*%d=%d" % (j, i, i*j), end="\t")
    i = i + 1
    print("")
Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐