能夠完成某個工做的代碼塊。這是能夠用來構建更大程序的一個小部分。函數
1) def 關鍵字ui
2)函數名及後面跟隨的括號spa
3)冒號與for循環,while循環,if語句中同樣code
提醒:函數沒被調用前不是主程序的一部分。orm
print_nums()blog
1)一個參數遊戲
def print_nums(num): for i in range(num): print(i) print_nums(3)
2)兩個參數:get
def add(n1, n2): print("{} + {} = ?".format(n1, n2)) print(n1 + n2) add(3, 5)
def add2(n1, n2, n3): print("{} + {} + {} = ?".format(n1, n2, n3)) print(n1 + n2 + n3) add2(3, 5, 9)
def add3(n1, n2): return n1 + n2 sum = add3(3, 5) print("sum = {}".format(sum))
def multi_table(num): i = 1 while i <= num: text = "" # for j in range(1, i+1): j = 1 while j <= i: text += "{}*{}={:2} ".format(i, j, i*j) j += 1 print(text) i += 1
def print_shape(row, col): for i in range(row): line = "" for j in range(col): line += "*" print(line)
def choice_box(): import easygui as g msg = "輸入你喜歡的顏色" title = "遊戲互動" choices = ["紅色", "綠色", "藍色", "青色"] return g.choicebox(msg, title, choices)