Skip to main content
 Web开发网 » 编程语言 » Python语言

python函数

2021年11月26日5640百度已收录

def display_message(message):

print("在本文学习了什么 ")

display_massage()

def favorite_book(message):

print(“hello.”+massage.title())

display_message("西游记")

# 定义一个为favorite_book()函数,其中包含一个名为title的行参数,打印一条“hello.message.title()”的消息,调用这个函数,并将一本书的名称作为实参传递给他。

‌位置实参(实参传递顺序很重要)

python必须将函数调用中的每个实参都关联到函数定义的一个行参,最简单的关联方式是基于实参的顺序,这种方式被称为位置实参。

def describe(animal,name):

print(" i hava "animal)

print("my animal"+names is name)

describe('dog','xiaohuang')

调用函数多次,在此基础上直接再调用一次def describe(animal,name):即可。

def describe(animal,name):

print(" i hava "animal)

print("my animal"+names is name)

describe('dog','xiaohuang')

describe('cat','tom')

‌关键字实参

关键字实参是传递给函数的名称-值对

关键字实参让你无需考虑函数调用中的实参顺序,还能清楚的指出函数调用中各个值的用途。

def describe(animal,name):

print(" i hava "animal)

print("my animal"+names is name.title())

describe(animal='dog',name='xiaohuang')

describe(animal='cat',name='tom')

使用关键字实参时,务必准确地指出函数定义中的行参名。

‌默认值

编写函数时,可给每个行参指定默认值。在调用函数中给形参提供了实参时,python将使用指定的实参值;否则将使用的形参的默认值。

def describe(name,animal='dog'):

print("i have a "animal)

print("my "+animal +"name is "+name.title())

describe(name='wille')

使用哪种调用方法都无关紧要,只要函数能生成你希望的输出就行。使用对你来说最容易理解的调用方式即可。

评论列表暂无评论
发表评论
微信