Python基础(二)
函数就是一段实现特定功能的代码,使用函数可以提高代码的重复利用率。Python 中有很多内置函数,比如之前常用的 print 函数,当内置函数不足以满足我们的需求时,我们还可以自定义函数。
创建函数
在 Python 中,使用 def 关键字定义函数:
def my_function():
print("Hello from a function")
调用函数
如需调用函数,请使用函数名称后跟括号:
def my_function():
print("Hello from a function")
my_function()
参数
参数在函数名后的括号内指定。根据需要添加任意数量的参数,只需用逗号分隔即可
def my_function(fname):
print(fname + " Gates")
my_function("Bill")
my_function("Steve")
my_function("Elon")
当我们不确定参数的个数时,可以使用不定长参数,在参数名前加 * 进行声明,格式如下所示
def my_function(*kids):
print("The youngest child is " + kids[2])
my_function("Phoebe", "Jennifer", "Rory")
默认参数值
如果调用了不带参数的函数,则使用默认值:
def my_function(country = "China"):
print("I am from " + country)
my_function("Sweden") # I am from Sweden
my_function("India") # I am from India
my_function() # I am from China
以 List 传参
def my_function(food):
for x in food:
print(x)
fruits = ["apple", "banana", "cherry"]
my_function(fruits)
关键字参数
使用 key = value 语法发送参数
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
my_function(child1 = "Phoebe", child2 = "Jennifer", child3 = "Rory")
返回值
如果需要让函数有返回值,就需要 return 语句:
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))