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
    

      运行结果:

     

  • 相关阅读:
    信号与系统04 离散时间傅里叶变换
    什么是吉布斯现象
    部分分式展开
    常见的傅里叶变换对
    微分运算的时域扩展
    动态库和静态库的制作与使用 【转载】原文链接https://www.cnblogs.com/WindSun/p/11287927.html
    派生访问说明符
    自定义异常类
    C++虚函数
    Linux知识点
  • 原文地址:https://www.cnblogs.com/lirongyang/p/9520234.html
Copyright © 2011-2022 走看看