DAY 05 - 函式

tags: python教學,函式,副程式

定義函式結構

def HW(): print("Hello World function")

此時只有定義,運行他不會動

HW() #輸出結果:Hello World function

傳入引數

def HW(name): print("Hello World", name)
HW("julian") #輸出結果:Hello World julian

練習:印出下列句子

「''」內的字請使用者輸入
I have a 'dog' and its name is 'tony'
I have a 'cat' and its name is 'candy'

返回值

輸入 台中市
輸入 清水區
輸入 436

輸出 台中市 清水區 436

def get_location(city, area, zipcode): location = city + ' ' + area + ' ' + zipcode return location

傳入串列

def call_student(names): for name in names: print("Hi, "+name) student = ["alan" , "jack" , "rose" , "bonny", "stan"] call_student(student)

傳入任意數量的引數到函式

names參數中的星號()會讓python建立一個名字為names的空多元組

def call_num_student(*names): for name in names: print("Hi, "+name) call_num_student("alan" , "jack" , "rose" , "bonny", "stan", "julian")

練習 - 自製平方函式 sqr(x)

解答
def sqr(num): return num*num

練習 - 最大公因數 gdc(x,y)

提示:while(x%y != 0)

解答
def gcd(x,y): tmp = 0 while(x%y != 0): tmp = y y = x%y x = tmp return y

HomeWork - 費氏數列(斐波那契数)

0,1,1,2,3,5,8,13,21,34,55,

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

解答

7/22