python初級(302) 4 函數

1、函數

一、函數定義:

能夠完成某個工做的代碼塊。這是能夠用來構建更大程序的一個小部分。函數

二、建立或定義函數要使用def關鍵字

三、建立一個函數

image

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)
3)三個參數:
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))

 

2、練習

一、打印乘法口訣表

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)
相關文章
相關標籤/搜索