• while嵌套循环案例


    一:使用Python的while嵌套循环打印如下图形:

    *
    * *
    * * *
    * * * *
    * * * * *

    i = 1
    while i <= 5:
        j = 1
        str = ''
        while j <= i:
            str = str + '* '
            j += 1
        print(str)
        i += 1

    *
    * *
    * * *
    * * * *
    * * * * *
    * * * *
    * * *
    * *
    *

     1 i = 1
     2 while i <= 5:
     3     j = 1
     4     str = ''
     5     while j <= i:
     6         str = str + '* '
     7         j+=1
     8     print(str)
     9     i+=1
    10 i = 4
    11 while i>=1:
    12     j=i
    13     str = ''
    14     while(j>=1):
    15         str = str + "* "
    16         j-=1
    17     print(str)
    18     i-=1

      总结:之前学的Java,写习惯了,Python有点不习惯,他的代码特别灵活,按行缩进,稍不注意就陷入死循环;但是很好玩;哈哈!

    二:Python嵌套循环输出九九乘法表

    1*1=1

    1*2=2 2*2=4

    1*3=3 2*3=6 3*3=9

    1*4=4 2*4=8 3*4=12 4*4=16

    1*5=5 2*5=10 3*5=15 4*5=20 5*5=25

    1*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36

    1*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49

    1*8=8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64

    1*9=9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81

    1 i = 1
    2 while i <= 9:
    3     j = 1
    4     while j <= i:
    5         print("%d*%d=%-2d"%(j,i,j * i), end=' ')
    6         j += 1
    7     print("
    ")
    8     i += 1

     三:实现简单的用户登录控制

     1 i =0
     2 userName = 'Python'
     3 userPassword = '123456'
     4 while i<3:
     5     name = input("请输入用户名:")
     6     password = input("请输入密码:")
     7     if(name==userName and password==userPassword):
     8         print("登陆成功!")
     9         break
    10     elif(name==userName):
    11         print("密码有误,请重新输入!")
    12     elif(password == userPassword):
    13         print("用户名输入有误,请重新输入!")
    14     else:
    15         print("用户名和密码错误!")
    16     i+=1;
    17     print("温馨提示:您还有%d次登录机会"%(3-i))
    18 print("今天登陆次数已达上限,今晚想想;明天再来哈!")
  • 相关阅读:
    文字编码转换器 V1.0 免费绿色版
    一把刀系统维护工具箱 v1.6 绿色版
    一把刀终极配置Win7/8版 v2.0 绿色版
    移动端 iframe的使用
    scale配合过渡的时候bug
    js 简体中文拼音对应表
    原生js快速渲染dom节点
    让我们的svg起飞,兼容ie9的神器
    盒模型
    Normalize.css 与 reset.css
  • 原文地址:https://www.cnblogs.com/le-ping/p/7787800.html
Copyright © 2020-2023  润新知