美文网首页
Python day 02

Python day 02

作者: 牧笛_ini | 来源:发表于2019-03-06 21:28 被阅读0次

    Default parameter in function

    you can set its default value when you define a function

    def power(x, n=2):
        s = 1
        while n > 0:
            n = n - 1
            s = s * x
        return s
    

    Note: the Mandatory parameter sshould placed in front of the default parameters

    Variable parameter

    if you add a star * in front of the parameter, this paramtere could be a list of tuple though you may not give it in the list form

    def calc(*numbers):
        sum = 0
        for n in numbers:
            sum = sum + n * n
        return sum
    calc(1,2,3)
    

    Recursive function

    def factorial(x):
        if x==1:
            return 1
        else:
            return x*factorial(x-1)
    

    Slice

    exactly like the function of : in matlab

    L=list(range(100))
    L[1:10]
    

    List Comprehensions

    powerful weapon
    you can use it to generate list with the help of for loop

    [x*(x-1) for x in range(100) if x%2==0]
    

    Generator

    相关文章

      网友评论

          本文标题:Python day 02

          本文链接:https://www.haomeiwen.com/subject/yjlfpqtx.html