Python - 函数

Python - 函数 首页 / Python3入门教程 / Python - 函数

函数是应用程序最重要的方面。可以将函数定义为可重用代码的组织块,可以在需要时调用它。

Python可以将大型程序划分为称为函数的基本构建块。该函数包含用{}括起来的一组编程语句。可以多次调用一个函数,以为Python程序提供可重用性和模块化。

Python为无涯教程提供了各种内置函数,例如 range() print()。虽然,用户可以创建其函数,这些函数可以称为用户定义的函数。

函数主要有两种。

  • 用户定义函数 -  用户定义的函数是由用户定义的函数,用于执行特定任务。
  • 内置函数         -  内置函数是在Python中预定义的那些函数。

在本教程中将讨论用户定义函数。

创建函数

Python提供了 def 关键字来定义函数。下面给出了define函数的语法。

def my_function(parameters):
      function_block
return expression

了解函数定义的语法。

  • def                        - 关键字以及函数名称用于定义函数。
  • my_function        - 标识符规则必须位于函数名称之后。
  • parameters           -  一个函数接受参数(参数),并且它们可以是可选的。
  • function_block    -  函数块以冒号(:)开头,并且块语句必须使用相同的缩进。
  • return                 - 语句用于返回值。一个函数只能有一个返回.

函数调用

在Python中,创建函数后,可以从另一个函数调用它。必须在调用函数之前定义一个函数。否则,Python解释器将给出错误。要调用该函数,请在函数名称后加上括号。

考虑以下简单示例,该示例显示消息" Hello World"。

#函数定义
def hello_world():  
    print("hello world")  
#函数调用
hello_world()    

输出:

hello world

return声明

在函数的末尾使用return声明,并返回函数的结果。它终止函数执行并将结果转移到调用函数的位置。return声明不能在函数之外使用。

return [expression_list]

它可以包含被求值的表达式,并将值返回给调用者函数。如果return语句没有表达式或该函数本身不存在,则它返回 None 对象。

考虑以下示例:

# 定义函数
def sum():
    a = 10
    b = 20
    c = a+b
    return c
# 打印语句中调用SUM()函数
print("The sum is:",sum())

输出:

The sum is: 30

在上面的代码中,定义了名为 sum 的函数,它具有一条语句 c = a + b ,该语句计算给定的值,并返回结果返回给调用者函数的语句。

示例2:创建没有返回语句的函数
# 定义函数
def sum():
    a = 10
    b = 20
    c = a+b
# 打印语句中调用sum()函数
print(sum())

输出:

None

在上面的代码中,无涯教程定义了没有return语句的相同函数,因为可以看到 sum()函数将 None 对象返回给了调用方函数。

函数参数

参数是可以传递给函数的信息类型。参数在括号中指定。可以传递任意数量的参数,但是必须用逗号将它们分开。

考虑以下示例,该示例包含一个接受字符串作为参数的函数。

#定义函数
def func (name):  
    print("Hi ",name) 
#函数调用
func("Devansh")   

输出:

Hi Devansh
例子2
#Python 函数来计算两个变量的总和
#定义函数
def sum (a,b):  
    return a+b;  
  
#用户输入值
a = int(input("Enter a: "))  
b = int(input("Enter b: "))  
  
#打印a和b的总和 
print("Sum = ",sum(a,b))  

输出:

Enter a: 10
Enter b: 20
Sum =  30

引用调用

在Python中,按引用调用意味着将实际值作为参数传递给函数。所有函数都通过引用调用,在函数内部对引用所做更改都将还原为引用的原始值。

例子1 Passing Immutable Object (List)
#定义函数
def change_list(list1):  
    list1.append(20) 
    list1.append(30)  
    print("list inside function = ",list1)  
  
#定义列表
list1 = [10,30,40,50]  
  
#调用该函数  
change_list(list1)
print("list outside function = ",list1)

输出:

list inside function =  [10, 30, 40, 50, 20, 30]
list outside function =  [10, 30, 40, 50, 20, 30]
示例2:传递可变对象(字符串)
#定义函数  
def change_string (str):  
    str = str + " Hows you "
    print("printing the string inside function :",str)
  
string1 = "Hi I am there"  
  
#调用该函数 
change_string(string1)  
  
print("printing the string outside function :",string1)  

输出:

printing the string inside function : Hi I am there Hows you 
printing the string outside function : Hi I am there

参数类型

在函数调用时可以传递几种类型的参数。

  1. 必需参数
  2. 关键字参数
  3. 默认参数
  4. 变长参数

必填参数

到目前为止,无涯教程已经了解了Python中的函数调用。但是可以在函数调用时提供参数。就所需的自变量而言,这些是在函数调用时需要传递的自变量,它们在函数调用和函数定义中的位置完全匹配。如果函数调用中未提供任何一个自变量,或者自变量的位置已更改,则Python解释器将显示错误。

例子1

def func(name):  
    message = "Hi "+name
    return message
name = input("Enter the name:")  
print(func(name))  

输出:

Enter the name: Learnfk
Hi Learnfk

例子2

#simple_interest的函数接受三个参数
def simple_interest(p,t,r):  
    return (p*t*r)/100  
p = float(input("Enter the principle amount? "))  
r = float(input("Enter the rate of interest? "))  
t = float(input("Enter the time in years? "))  
print("Simple Interest: ",simple_interest(p,r,t))  

输出:

Enter the principle amount: 5000
Enter the rate of interest: 5
Enter the time in years: 3
Simple Interest:  750.0

示例3

#该函数计算返回两个参数A和B的总和 
def calculate(a,b):  
    return a+b  
calculate(10) # 这会导致错误,因为我们缺少所需的参数b。 

输出:

TypeError: calculate() missing 1 required positional argument: 'b'

默认参数

Python允许在函数定义处初始化参数。如果在函数调用时未提供任何参数的值,那么即使未在函数调用中指定参数,也可以使用定义中给出的值来初始化该参数。

例子1

def printme(name,age=22):  
    print("My name is",name,"and age is",age)  
printme(name = "john")

输出:

My name is Learnfk and age is 22

例子2

def printme(name,age=22):  
    print("My name is",name,"and age is",age)  
printme(name = "john") #变量年龄未传递到该功能,但函数中考虑了默认值的年龄
printme(age = 10,name="David") #这里覆盖的年龄值,10将作为年龄打印

输出:

My name is john and age is 22
My name is David and age is 10

可变长度参数(* args)

在大型项目中,有时无涯教程可能不知道要预先传递的参数数量。在这种情况下,Python使可以灵活地提供逗号分隔的值,这些值在函数调用时在内部被视为元组。通过使用可变长度参数,可以传递任意数量的参数。

但是,在函数定义中使用* args(星号)定义为* <variable-name>可变长度参数。

示例

def printme(*names):  
    print("type of passed argument is ",type(names))  
    print("printing the passed arguments...")  
    for name in names:  
        print(name)  
printme("john","David","smith","nick")  

输出:

type of passed argument is  <class 'tuple'>
printing the passed arguments...
john
David
smith
nick

在上面的代码中,无涯教程传递了 * names 作为可变长度参数。调用了函数并传递了在内部被视为元组的值。元组是一个与列表相同的可迭代序列。要打印给定的值,使用for循环迭代 * arg名称

关键字参数(** kwargs)

Python允许使用关键字参数调用函数。这种函数调用将使能够以随机顺序传递参数。

参数的名称被视为关键字,并在函数调用和定义中匹配。如果找到相同的匹配项,则将参数的值复制到函数定义中。

例子1

#功能func用名称和消息调用为关键字参数
def func(name,message):  
    print("printing the message with",name,"and ",message)  
    
    #名称和消息分别复制了VeameSfk和Hello 
    func(name = "Learnfk",message="hello") 

输出:

printing the message with Learnfk and  hello

例子2 在调用时以不同顺序提供值

#使用关键字参数调用函数simple_interest(p,t,r),在这种情况下,参数的顺序无关紧要 
def simple_interest(p,t,r):  
    return (p*t*r)/100  
print("Simple Interest: ",simple_interest(t=10,r=10,p=1900))   

输出:

Simple Interest:  1900.0

如果在函数调用时提供不同的参数名称,将引发错误。

示例3

#使用关键字参数调用simple_interest(p,t,r)函数.   
def simple_interest(p,t,r):  
    return (p*t*r)/100  

#没有找到参数名称的完全匹配(关键字)  
print("Simple Interest: ",simple_interest(time=10,rate=10,principle=1900)) 

输出:

TypeError: simple_interest() got an unexpected keyword argument 'time'

Python允许在函数调用时提供所需参数和关键字参数的混合。但是,不得在关键字参数之后给出必需的参数,即,一旦在函数调用中遇到关键字参数,则以下参数也必须是关键字参数。

示例4

def func(name1,message,name2):  
    print("printing the message with",name1,",",message,",and",name2)  
#the first argument is not the keyword argument  
func("Learnfk",message="hello",name2="David") 

输出:

printing the message with Learnfk , hello ,and David

以下示例将由于在函数调用中传递的关键字和必需参数的不正确混合而导致错误。

示例5

def func(name1,message,name2): 
    print("printing the message with",name1,",",message,",and",name2)  
func("Learnfk",message="hello","David")      

输出:

SyntaxError: positional argument follows keyword argument

Python提供了传递多个关键字参数的工具,这些参数可以表示为 ** kwargs 。它与 * args 类似,但它以字典格式存储参数。

示例6:使用关键字参数

def food(**kwargs):
    print(kwargs)
food(a="Apple")
food(fruits="Orange", Vagitables="Carrot")

输出:

{'a': 'Apple'}
{'fruits': 'Orange', 'Vagitables': 'Carrot'}

变量范围

变量的范围取决于声明变量的位置。在程序的一个部分中声明的变量可能无法被其他部分访问。

在python中,变量是用两种类型的作用域定义的。

  1. 全局变量
  2. 局部变量

已知在任何函数外部定义的变量具有全局范围,而已知在函数内部定义的变量具有局部范围。

考虑以下示例。

例子1 局部变量

def print_message():  
    message = "hello !! I am going to print a message." 
    print(message)  
print_message()  
print(message) # 由于此处无法访问局部变量,这将导致错误。    

输出:

hello !! I am going to print a message.
  File "/root/PycharmProjects/PythonTest/Test1.py", line 5, in 
    print(message)
NameError: name 'message' is not defined

例子2 全局变量

def calculate(*args):  
    sum=0  
    for arg in args:  
        sum = sum +arg  
    print("The sum is",sum)  
sum=0  
calculate(10,20,30) #60将作为总和 
print("Value of sum outside the function:",sum) # 0将被打印输出:

输出:

The sum is 60
Value of sum outside the function: 0

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

微服务架构核心20讲 -〔杨波〕

深入拆解Java虚拟机 -〔郑雨迪〕

Java并发编程实战 -〔王宝令〕

Vue开发实战 -〔唐金州〕

重学线性代数 -〔朱维刚〕

用户体验设计实战课 -〔相辉〕

手把手教你玩音乐 -〔邓柯〕

零基础GPT应用入门课 -〔林健(键盘)〕

结构执行力 -〔李忠秋〕

好记忆不如烂笔头。留下您的足迹吧 :)