zoukankan      html  css  js  c++  java
  • Python学习笔记控制之for循环和while循环

    随笔记录方便自己和同路人查阅。

    #------------------------------------------------我是可耻的分割线-------------------------------------------

      实际上for循环可以实现的功能while循环也可以实现,for循环只是更简洁。

    让我们来看下面的几个例子,分别使用for和while实现100之内的整数相加和打印99乘法表。

    #------------------------------------------------我是可耻的分割线-------------------------------------------

      计算100之内的整数相加

    #
    # -*- coding:utf-8 -*-
    # Autor: Li Rong Yang
    #for循环计算100以内整数相加
    total = 0
    for i in range(101):
        total += i
        print(total)
    #while循环计算100以内整数相加
    count = 0
    total=0
    while count<101:
        total = total+count
        print(total)
        count +=1
    

      

      运行结果:

      打印99乘法表

    #
    # -*- coding:utf-8 -*-
    # Autor: Li Rong Yang
    print("for循环打印99乘法表")
    for i in range(1,10):
        for b in range(1,10):
            print("%d*%d=%2d" % (i,b,i*b),end=" ")
        print()
    print("while循环打印99乘法表")
    count = 1
    while count < 10:
        for j in range(1,10):
                print("%d*%d=%2d" % (count,j,count*j),end=" ")
        print("")
        count +=1
    

      运行结果:

      

      左上三角打印99乘法表

    print("for循环打印左上角99乘法表")
    for i in range(1,10):
        for b in range(i,10):
            print("%d*%d=%2d" % (i,b,i*b),end=" ")
        print()
    print("while循环打印左上角99乘法表")
    count = 1
    while count < 10:
        for j in range(count,10):
                print("%d*%d=%2d" % (count,j,count*j),end=" ")
        print("")
        count +=1
    

        运行结果:  

      左下三角打印99乘法表

    print("for循环打印左下角99乘法表")
    for i in range(1,10):
        for b in range(1,i+1):
            print("%d*%d=%2d" % (i,b,i*b),end=" ")
        print()
    print("while循环打印左下角99乘法表")
    count = 1
    while count < 10:
        for j in range(1,count+1):
                print("%d*%d=%2d" % (count,j,count*j),end=" ")
        print("")
        count +=1
    

      运行结果:

     

  • 相关阅读:
    软件测试工具
    nat 转发
    修改Oracle 10g Express Edition的字符集
    java数字证书学习笔记
    【Java–XML】JDOM解析XML字符串(非XML文档)
    JAVA Web快速开发部署(Javarebel实现真正高效的tomcat热部署)
    热天稀饭配方
    javascript 使用正则实现replaceall功能
    设置eclipse中各类型文件的默认浏览器(如设置flex的.mxml的编辑器为MXML Editor)
    GAE中JDO数据清除
  • 原文地址:https://www.cnblogs.com/lirongyang/p/9520234.html
Copyright © 2011-2022 走看看