def test1(): '以元組的形式返回' return 1,2,3 d=test1() print(d) print(d[0]) print(test1()[1]) #輸出結果: #(1, 2, 3) #1 #2
def test2(): return 1,2,3 a,b,c=test2() print(a,b) print(c) d=test2() print(d) #1 2 #3 #(1,2,3)
return的返回值可以自定義返回形式,可以是列表或者元組。如果沒有自定義,將以元組的形式返回結果。
新建一個函數 In [1]: def nums(): ...: a = 11 ...: b = 22 ...: c = 33 ...: return [a,b,c] #以列表的方式返回 ...: #調用函數 ...: nums() ...: ...: #函數返回值 Out[1]: [11, 22, 33] # 新建一個函數 In [2]: def nums(): ...: a = 11 ...: b = 22 ...: c = 33 ...: return (a,b,c) #以元祖的方式返回 ...: #調用函數 ...: nums() ...: ...: #函數返回值 Out[2]: (11, 22, 33) # 新建一個函數 In [3]: def nums(): ...: a = 11 ...: b = 22 ...: c = 33 ...: return a,b,c #以元祖的方式返回的另一種形式 ...: #調用函數 ...: nums() ...: ...: #函數返回值 Out[3]: (11, 22, 33)