Python allows function arguments to have default values. If the function is called without the argument, the argument gets its default value.
When we define default arguments, we have to put all of them at the end; otherwise, we will see:
SyntaxError: non-default argument follows default argument
When we define functions, we can give default arguments; when we invoke functions, we can give keyword arguments. (They both look alike, but they are different !!)
default argument 是我們在寫function 中 定義好先預設的argument
keyword argument 是要跑function 時,給定要代入 argument 優先性會先吃 keyword arguement input
print(sum(n1=200)) #keyword argument
# default argument
def sum(n1, n2):
return n1 + n2
print(sum(2, 3))
# print(sum(2, )) # show missing 1 required positional argument
def sum(n3=5, n4): #non-default argument follows default argument
return n3 * n4
print(sum(2, )) #它會不知道你是要用 argument 代入還是default arguemnt 代入
def sum(n3, n4=5): # default arguemnt 放在最後 OK
return n3 * n4
print(sum(2, )) # 抓 n3 = 2, n4 原本argument 沒寫, 用default n=5 代入
----------------------------------------
10
# default and keyword argument comparison
def sum(n1=0, n2=0): # default argument
return n1 + n2
#keyword argument
print(sum(n1=200))
---------------------------------
200