个性化阅读
专注于IT技术分析

Python函数定义和用法详细解读

点击下载

本文概述

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

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

换句话说, 我们可以说功能集合创建了一个程序。该功能在其他编程语言中也称为过程或子例程。

Python为我们提供了各种内置函数, 例如range()或print()。虽然, 用户可以创建其功能, 这些功能可以称为用户定义功能。

Python函数的优势

Python函数具有以下优点。

  • 通过使用函数, 我们可以避免在程序中一次又一次地重写相同的逻辑/代码。
  • 我们可以在程序中以及在程序的任何位置多次调用python函数。
  • 当大型python程序分为多个功能时, 我们可以轻松地对其进行跟踪。
  • 可重用性是python函数的主要成就。
  • 但是, 在python程序中, 函数调用始终是开销。

创建一个功能

在python中, 我们可以使用def关键字定义函数。下面给出了在python中定义函数的语法。

def my_function():
	function-suite 
	return <expression>

该功能块以冒号(:)开始, 所有相同级别的块语句均保持相同的缩进。

一个函数可以接受在定义和函数调用中必须相同的任意数量的参数。

函数调用

在python中, 必须在调用函数之前定义一个函数, 否则python解释器会给出错误。定义函数后, 我们可以从另一个函数或python提示符中调用它。要调用该函数, 请在函数名称后加上括号。

下面给出了一个打印消息” Hello Word”的简单功能。

def hello_world():
	print("hello world")

hello_world()

输出

hello world

功能参数

信息可以作为参数传递到函数中。参数在括号中指定。我们可以提供任意数量的参数, 但是必须用逗号将它们分开。

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

例子1

#defining the function
def func (name):
	print("Hi ", name);

#calling the function 
func("Ayush")

例子2

#python function to calculate the sum of two variables 
#defining the function
def sum (a, b):
	return a+b;

#taking values from the user
a = int(input("Enter a: "))
b = int(input("Enter b: "))

#printing the sum of a and b
print("Sum = ", sum(a, b))

输出

Enter a: 10
Enter b: 20
Sum =  30

在Python中通过引用调用

在python中, 所有函数均按引用调用, 即, 函数内部对引用所做的所有更改都将还原为引用所引用的原始值。

但是, 在可变对象的情况下有一个例外, 因为对可变对象(如字符串)所做​​的更改不会还原为原始字符串, 而是会生成新的字符串对象, 因此会打印两个不同的对象。

示例1:传递不可变对象(列表)

#defining the function
def change_list(list1):
	list1.append(20);
	list1.append(30);
	print("list inside function = ", list1)

#defining the list
list1 = [10, 30, 40, 50]

#calling the function 
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:传递可变对象(字符串)

#defining the function
def change_string (str):
	str = str + " Hows you";
	print("printing the string inside function :", str);

string1 = "Hi I am there"

#calling the function
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

#the argument name is the required argument to the function func 
def func(name):
    message = "Hi "+name;
    return message;
name = input("Enter the name?")
print(func(name))

输出

Enter the name?John
Hi John

例子2

#the function simple_interest accepts three arguments and returns the simple interest accordingly
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? 10000
Enter the rate of interest? 5
Enter the time in years? 2
Simple Interest:  1000.0

例子3

#the function calculate returns the sum of two arguments a and b
def calculate(a, b):
    return a+b
calculate(10) # this causes an error as we are missing a required arguments b.

输出

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

关键字参数

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

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

考虑以下示例。

例子1

#function func is called with the name and message as the keyword arguments
def func(name, message):
    print("printing the message with", name, "and ", message)
func(name = "John", message="hello") #name and message is copied with the values John and hello respectively

输出

printing the message with John and  hello

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

#The function simple_interest(p, t, r) is called with the keyword arguments the order of arguments doesn't matter in this case
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

#The function simple_interest(p, t, r) is called with the keyword arguments. 
def simple_interest(p, t, r):
    return (p*t*r)/100

print("Simple Interest: ", simple_interest(time=10, rate=10, principle=1900)) # doesn't find the exact match of the name of the arguments (keywords)

输出

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)
func("John", message="hello", name2="David") #the first argument is not the keyword argument

输出

printing the message with John , hello , and David

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

例子5

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

输出

SyntaxError: positional argument follows keyword argument

默认参数

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

例子1

def printme(name, age=22):
    print("My name is", name, "and age is", age)
printme(name = "john") #the variable age is not passed into the function however the default value of age is considered in the function

输出

My name is john and age is 22

例子2

def printme(name, age=22):
    print("My name is", name, "and age is", age)
printme(name = "john") #the variable age is not passed into the function however the default value of age is considered in the function
printme(age = 10, name="David") #the value of age is overwritten here, 10 will be printed as age

输出

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

可变长度参数

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

但是, 在函数定义中, 我们必须将带有*(星号)的变量定义为* <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

变量范围

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

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

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

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

考虑以下示例。

例子1

def print_message():
    message = "hello !! I am going to print a message." # the variable message is local to the function itself
    print(message)
print_message()
print(message) # this will cause an error since a local variable cannot be accessible here.

输出

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 will be printed as the sum
print("Value of sum outside the function:", sum) # 0 will be printed

输出

The sum is 60
Value of sum outside the function: 0
赞(0)
未经允许不得转载:srcmini » Python函数定义和用法详细解读

评论 抢沙发

评论前必须登录!