Python函数的定义
函数是可重复使用的,用来实现单一或关联功能的代码段。
函数能提高应用的模块性,和代码的重复利用率。除了Python提供的内建函数,比如print(),也可以自定义函数。
Python函数的语法
函数代码块以 def 关键词开头,后接函数标识符名称和圆括号 ()。
任何传入参数和自变量必须放在圆括号中间,圆括号之间可以用于定义参数。
函数的第一行语句可以选择性地使用文档字符串—用于存放函数说明。
函数内容以冒号 : 起始,并且缩进。
return [表达式] 结束函数,选择性地返回一个值给调用方,不带表达式的 return 相当于返回 None。
def 函数名(参数列表):
函数体
使用函数输出"Hello World!":
def hello():
print("hello word")
hello()
Python函数的使用
拿一个稍微复杂一点点的例子看看。目标:比较两个数大小,如果a大于b,则输出a,否则提示要重新输入。
需求非常简单,这篇文章主要通过两种实现方式对比来直观的看到函数的作用。
不使用函数实现:
#coding=utf-8
#coding by tanli
a=input("please input a:")
b=input("please input b:")
print (a)
print (b)
if a>b:
print (a)
else:
print ("please input again")
程序运行结果:
please input a:5
please input b:8
5
8
please input again
使用函数来实现:
#coding=utf-8
#coding by tanli
def getResult(a,b):
#定义一个命名为GetResult的方法,注意方法名首字母要小写,其后单词的首字母要大写
if a > b:
return a
else:
return "please input again"
a=input("please input a:")
b=input("please input b:")
print(a)
print(b)
print (getResult(a,b))
相关资源:
http://www.dcsdn.com/doc/do-3728
http://www.dcsdn.com/doc/do-3662
http://www.dcsdn.com/doc/d-3573
版权声明:本文为CSDN博主「Holidaylovesam」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/alice_tl/article/details/78388079