python函数定义如何使用
定义一个函数
使用关键字def告诉Python你将要定义一个函数。
给你的函数起一个名字。函数名应当能表明函数是干什么的。
给函数需要的数据起名称。
它们是变量名,而且只在函数里用。
这些名称被称为函数的参数(arguments)
确保函数的定义以冒号结束。
在函数内部,写下任意你想要的代码。
使用你的函数
函数名后跟圆括号调用函数。
在圆括号中,给出函数运行需要的数据。
函数中的参数可以是变量,例如current_name和current_age,也可以是实际的数据,例如'eric'和5。
第一个例子
第一个简单的例子,我们实现一个道贺的程序。我们先实现一个不用函数的版本,尝试去理解函数的作用。如下所示:
print("Youaredoinggoodwork,Adriana!")
print("Thankyouverymuchforyoureffortsonthisproject.")
print("\nYouaredoinggoodwork,Billy!")
print("Thankyouverymuchforyoureffortsonthisproject.")
print("\nYouaredoinggoodwork,Caroline!")
print("Thankyouverymuchforyoureffortsonthisproject.")
上述代码有很多重复的地方,函数就是用来替代重复的代码,在需要的地方引用它。使用函数后的代码如下所示:
defthank_you(name):
#Thisfunctionprintsatwo-linepersonalizedthankyoumessage.
print("\nYouaredoinggoodwork,%s!"%name)
print("Thankyouverymuchforyoureffortsonthisproject.")
thank_you('Adriana')
thank_you('Billy')
thank_you('Caroline')
在初始代码中,每条被打印的语句中,除了名字其他部分都是相同的。当你看到这样的重复语句后,就可以使用函数使你的程序更有效率。
以上内容为大家介绍了python培训之函数定义如何使用,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注IT培训机构:千锋教育。

相关推荐HOT
更多>>
python函数标注是什么
python函数标注是什么在参数的使用方法中,还有一种解包的情况是需要我们掌握的。比如,将列表或者字典的值转换为函数的参数,就需要用到参数解...详情>>
2023-11-14 14:13:35
python正负索引的使用
python正负索引的使用本文教程操作环境:windows7系统、Python3.9.1,DELLG3电脑。1、说明使用正索引(从左至右)、负索引(从右至左)访问元素,时...详情>>
2023-11-14 13:45:04
python垃圾回收的机制过程
python垃圾回收的机制过程本文教程操作环境:windows7系统、Python3.9.1,DELLG3电脑。1、步骤(1)收集所有容器对象(list,dict,tuple,customClas...详情>>
2023-11-14 13:05:15
pythontry语句的执行原理
pythontry语句的执行原理1、原理分析(1)执行try子句(try和except关键字之间的多行语句)。(2)如果没有异常发生,则跳过except子句并完成try语句...详情>>
2023-11-14 09:37:35热门推荐
技术干货






