Python条件语句与循环

发布时间:2019-09-20 07:31:08编辑:auto阅读(1253)

    1、判断与循环
    python 缩进
    main:
    print("Hello")
    print("Hello world.")

    if 判断条件:
        执行语句
    elif 判断条件:
        执行语句
    else:
        执行语句
    while 判断条件:
        执行语句
    a = 100
    while a>1:
        print(a)
        a-=1
        if a==50:
            break   # 退出循环
        if a==55:
            print("5555555555")
            continue   # 此次循环结束,进入下一个循环

    break 跳出循环
    continue 进入下一次循环

    for item in sequence:
       执行语句
    l = ["a","b","c","d","e","f"]
    print(l[:])
    print(l[0:5])        # 大于等于0     小于5  0 <= a > 5
    print(l[0:-1])        # 大于等于0     小于5  0 <= a > 5
    for x,y in enumerate(l):    # 打印列表中元素以及下标
        print(x,y)

    2、编程思想最重要

    编程语言最重要的是思想
    ABCD乘以9=DCBA,求A=?,B=?,C=?,D=?

    for A in range(1,10):
        for B in range(0,10):
            for C in range(0,10):
                for D in range(1,10):
                    start = 1000*A+100*B+10*C+D
                    end = 1000*D+100*C+10*B+A
                    if start * 9 == end:
                        print("A={}".format(A))
                        print("B={}".format(B))
                        print("C={}".format(C))
                        print("D={}".format(D))
                        print("{0} * 9 = {1}".format(start,end))

    返回结果:
    A=1
    B=0
    C=8
    D=9
    1089 * 9 = 9801

    3、求阶乘
    求1-n的阶乘的和
    1!+ 2!+ 3!+ 4!+5 !+ ··· + n!
    0! = 1
    1!= 1
    2!= 1 2 = 2
    3!= 1
    2 * 3 = 6

    def one(n):
        total = 1
        if n ==0:
            total = 1
        else:
            for i in range(1,n+1):
                total *= i
        return total
    print(one(3))
    
    status=1
    while status:
        result = 0
        n= input("Please input a number(n>=0) : ")
        for i in n:
            if not i.isdigit():
                print("The number of you input is error.")
                exit(1)
        if int(n) < 0:
            print("The number of you input is error.")
            break
        for i in range(0,int(n)+1):
            result += one(i)
        print("0! + 1! + 2! + ··· ··· + n! = {}".format(result))

关键字

上一篇: python unittest框架

下一篇: H3C--MSTP配置