1. 程式人生 > >【20171002】python_語言設計(3)函式

【20171002】python_語言設計(3)函式

1.函式定義
完成特定功能的一個語句組,函式可以反饋結果
為函式提供不同的引數,可以實現對不同資料的處理。
自定義函式、系統自帶函式(python內嵌函式,標準庫函式、圖形庫)
使用函式的目的:降低程式設計的難度、程式碼重用
函式定義:def語句。def (<引數>):

形式引數、實際引數
函式呼叫:(<引數>)
return語句:結束函式呼叫,並將結果返回給呼叫者。

#列印生日快樂
def happy():
    print("happy birthday to you !")
def main(str1):
    happy()
    happy()
    print("happy birthday to"
+"dear "+str1) happy() main("mike")

2.函式呼叫和返回值
無返回值:return None
返回值可以是變數和表示式,可以返回一個或多個。

#兩點間距離
import math
def distance(x1,x2,y1,y2):
    a=(x1-x2)*(x1-x2)
    b=(y1-y2)*(y1-y2)
    dist=math.sqrt(a+b)
    return dist 
def main():
    x1,y1,x2,y2=eval(input())
    distance(x1,x2,y1,y2)
    print("distance="
,distance(x1,x2,y1,y2)) main()
#三角形周長
import math
def square(x):
    return x*x  
def distance(x1,y1,x2,y2)
    dist=math.sqrt(square(x1-x2)+square(y1-y2))
    return dist
def isTriangle(x1,y1,x2,y2,x3,y3):
    flag=((x1-x2)*(y3-y2)-(x3-x2)*(y1-y2))!=0
    return flag
def main():
    print("輸入三個點的座標:"
) x1,y1=eval(input()) x2,y2=eval(input()) x3,y3=eval(input()) if(isTriangle(x1,y1,x2,y2,x3,y3)): perim=distance(x1,y1,x2,y2)+distance(x2,y2,x3,y3)+distance(x1,y1,x3,y3) else : print("wrong!") main()

3.改變引數的函式值

#銀行利率計算
def addInterest(balance,rate):
    newBalance=balance*(1+rate)
    return newBalance
    #balance=newBalance
def main():
    amount=1000
    rate=0.05
    amount=addInterest(amount,rate)
    print(amount)
main()
#多個銀行賬戶的程式利率計算
def addInterest(balance,rate):
    for i in range(len(balances))
        balance[i]=balance[i]*(1+rate)
def main():
    amounts=[1000,105,3500,739]
    rate=0.05
    addInterest(amounts,rate)
    print(amounts)
main()

4.函式程式結構與遞迴


def createTable(principle,apr):
    #為每一年繪製星號的增長圖
    for year in range(1,11):
        principle=principle*(1+apr)
        print("%2d"%year,end='')
        total=caculateNum(principle)
        print("*"*total)
    print(" 0.0K   2.5K   5.0K  7.5K  10.0K")
def caculateNum(principle):
    #計算星號數量
    total=int(principle*4/1000.0)
    return total
def main():
    print("This program plots the growth of a 10-year investment")
    #輸入本金和利率
    principle=eval(input("enter the initial principal: "))
    apr=eval(input("enter the rate:"))
    #建立圖表
    createTable(principle,apr)
main()

遞迴計算

#遞迴
def fact(n):
    if n==0:
        return 1
    else :
        return n*fact(n-1)
def main():
    print(fact(3))

main()
#字串反轉
def reverse(s):
    if s=="":
        return s
    else :
        return reverse(s[1:])+s[0]
def main():
    print(reverse("ajdifjoi"))

main()

5.函式例項分析

# drawtree.py

from turtle import Turtle, mainloop

def tree(plist, l, a, f):
    """ plist is list of pens
    l is length of branch
    a is half of the angle between 2 branches
    f is factor by which branch is shortened
    from level to level."""
    if l > 5: #
        lst = []
        for p in plist:
            p.forward(l)#沿著當前的方向畫畫Move the turtle forward by the specified distance, in the direction the turtle is headed.
            q = p.clone()#Create and return a clone of the turtle with same position, heading and turtle properties.
            p.left(a) #Turn turtle left by angle units
            q.right(a)# turn turtle right by angle units, nits are by default degrees, but can be set via the degrees() and radians() functions.
            lst.append(p)#將元素增加到列表的最後
            lst.append(q)
        tree(lst, l*f, a, f)



def main():
    p = Turtle()
    p.color("green")
    p.pensize(5)
    #p.setundobuffer(None)
    p.hideturtle() #Make the turtle invisible. It’s a good idea to do this while you’re in the middle of doing some complex drawing,
    #because hiding the turtle speeds up the drawing observably.
    #p.speed(10)
   # p.getscreen().tracer(1,0)#Return the TurtleScreen object the turtle is drawing on.
    p.speed(10)
    #TurtleScreen methods can then be called for that object.
    p.left(90)# Turn turtle left by angle units. direction 調整畫筆

    p.penup() #Pull the pen up – no drawing when moving.
    p.goto(0,-200)#Move turtle to an absolute position. If the pen is down, draw line. Do not change the turtle’s orientation.
    p.pendown()# Pull the pen down – drawing when moving. 這三條語句是一個組合相當於先把筆收起來再移動到指定位置,再把筆放下開始畫
    #否則turtle一移動就會自動的把線畫出來

    #t = tree([p], 200, 65, 0.6375)
    t = tree([p], 200, 65, 0.6375)

main()