Return Key
The Python return keyword exits a function and instructs Python to continue executing the main program. The return keyword can send a value from a function or method, back to the main program; the returned value could be a string, a tuple, or any other object.
Python function default return value is None, and it’s always optional to return something from a function.
If the return keyword is placed in a loop, it will terminate the loop (迴圈會被停掉)
# return keyword
def myAddtion(a, b):
print(a + b)
def myAddtion2(a, b):
return a + b # return value 方便運算
myAddtion(10, 18)
myAddtion(20, 28)
myAddtion(30, 38)
myAddtion2(10, 18) # 只有return value 要有variable 存入 --> result 1
myAddtion2(20, 28) # 只有return value 要有variable 存入 --> result 2
myAddtion2(30, 38) # 只有return value 要有variable 存入 --> result 3
result1 = myAddtion2(10, 18)
result2 = myAddtion2(20, 28)
result3 = myAddtion2(30, 38)
print(myAddtion2(10, 18) + myAddtion2(20, 28) +
myAddtion2(30, 38)) # 利用return value 可以相加
print(result1 + result2 + result3)
print(myAddtion(10, 18), myAddtion(20, 28)) # print 出來的是none type
print(myAddtion(10, 18) + myAddtion(20, 28) + myAddtion(30, 38)) # none type
--------------------------------------------------------------------
[Running] python -u "d:\\2022_python_全攻略\\54. Parameters are local variables.py"
28
48
68
144 #print(myAddtion2(10, 18) + myAddtion2(20, 28) + myAddtion2(30, 38)) # 利用return value 可以相加
144 #print(result1 + result2 + result3)
28 # print(myAddtion(10, 18), myAddtion(20, 28)) # print 出來的是none type
48
None None
print(myAddtion(10, 18) + myAddtion(20, 28) + myAddtion(30, 38)) # none type
TypeError: unsupported operand type(s) for +: 'NoneType' and 'NoneType'
#return loop stop code
def myAddtion(a, b):
for i in range(a):
for j in range(b):
if i == 2 and j == 2:
return # default 是none 所以不一定要寫值,loop 在 (2,2)condition會停掉
print(i, j)
myAddtion(4,4) --> 原本預計跑到3, 3 但設定跑到 2,2 return 就stop
-------------------------------------------------------------
[Running] python -u "d:\\2022_python_全攻略\\tempCodeRunnerFile.py"
0 0
0 1
0 2
0 3
1 0
1 1
1 2
1 3
2 0
2 1 --> 2, 2時 return