函数 Function
def get_choices():
player_input = input("input:")
player_choice_internal = "rock"
return player_input
Parameter and return
def get_win(player, computer):
return [player, computer]
def hello():
return "name", 8
print(hello()) # ("name", 8)
Variable Scope
age = 8
def test():
print(age)
print(page) # 8
test() # 8
Nested Fucntions
def talk(phrase):
def say(word):
print(word)
words = phrase.split(" ")
for word in words:
say(word)
talk("I am going to buy the milk")
Error without 'nonlocal'
def count1():
count = 0
def increment():
nonlocal count # 嵌入式函数中的无法访问外层的变量
count += 1
print(count)
increment()
count1()
count_v = 0
def count2():
print(count_v) # count_v 是全局变量,所以可访问到
count2()
Error without 'global'
count_v = 0
def count2():
global count_v # 需要标明此变量是全局变量
count_v += 1 # 无法仅凭借这行修改,因为无法找到本地变量,也不知道 count_v 是全局变量
print(count_v)
count2()
Closure
def counter():
count = 0
def increment():
nonlocal count # 嵌入式函数中的无法访问外层的变量
count += 1
print(count)
return increment
increment = counter()
increment() # 1
increment() # 2
increment() # 3
Lambda Functions
lambda num : num * 2
multiply = lambda a, b : a * b
multiply(2, 4) # 8
*args and **kwargs
- *args: Non-Keyword Arguments
- **kwargs: Keyword Arguments
*args
def myFun(*argv):
for arg in argv:
print(arg)
myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks')
# Hello
# Welcome
# to
# GeeksforGeeks
def myFun(arg1, *argv):
print("First argument :", arg1)
for arg in argv:
print("Next argument through *argv :", arg)
myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks')
# First argument : Hello
# Next argument through *argv : Welcome
# Next argument through *argv : to
# Next argument through *argv : GeeksforGeeks
**kwargs
def myFun(**kwargs):
for key, value in kwargs.items():
print("%s == %s" % (key, value))
myFun(first='Geeks', mid='for', last='Geeks')
# first == Geeks
# mid == for
# last == Geeks
def myFun(arg1, **kwargs):
for key, value in kwargs.items():
print("%s == %s" % (key, value))
# Driver code
myFun("Hi", first='Geeks', mid='for', last='Geeks')
# first == Geeks
# mid == for
# last == Geeks
Using both *args and **kwargs in Python to call a function
def myFun(arg1, arg2, arg3):
print("arg1:", arg1)
print("arg2:", arg2)
print("arg3:", arg3)
# Now we can use *args or **kwargs to
# pass arguments to this function :
args = ("Geeks", "for", "Geeks")
myFun(*args)
kwargs = {"arg1": "Geeks", "arg2": "for", "arg3": "Geeks"}
myFun(**kwargs)
def myFun(*args, **kwargs):
print("args: ", args)
print("kwargs: ", kwargs)
# Now we can use both *args ,**kwargs
# to pass arguments to this function :
myFun('geeks', 'for', 'geeks', first="Geeks", mid="for", last="Geeks")