《Python语言程序设计》课件-第四章 (中英文课件)_第1页
《Python语言程序设计》课件-第四章 (中英文课件)_第2页
《Python语言程序设计》课件-第四章 (中英文课件)_第3页
《Python语言程序设计》课件-第四章 (中英文课件)_第4页
《Python语言程序设计》课件-第四章 (中英文课件)_第5页
已阅读5页,还剩74页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

Python语言程序设计【函数的定义和调用】PythonLanguageProgramming[Definitionandinvocationoffunctions]def

function_name(arg1,arg2[,...]): statement [returnvalue]知识点【函数的定义和调用】函数定义示例函数的调用def函数名(参数列表):

函数体defsumOf(a,b):

returna+ba=1

b

=2

c=sumOf(a,b)

print(str(c))1.函数通过def定义注意:该行结尾一定要加上冒号!!def

function_name(arg1,arg2[,...]): statement [returnvalue]KnowledgePoints[Definitionandinvocationoffunctions]functiondefinitionExamplefunctioniscalledDeffunctionname(parameterlist):

functionbodydefsumOf(a,b):

returna+ba=1

b

=2

c=sumOf(a,b)

print(str(c))1.FunctionsaredefinedbydefNote:Makesuretoputacolonattheendofthatline!!!!def

function_name(arg1,arg2[,...]): statement [returnvalue]知识点【函数的定义和调用】2.函数名的要求(1)函数名必须以下划线或字母开头,可以包含任意字母、数字或下划线的组合。不能使用任何的标点符号,空格也不可以;(2)函数名是区分大小写的;(3)函数名不能用保留字。3.函数形参和实参函数中的参数名称为‘形参’,调用函数时传递的值为‘实参’。def

function_name(arg1,arg2[,...]): statement [returnvalue]2.Requirementsforfunctionnames(1)functionnamemuststartwithanunderscoreorletter,cancontainanycombinationofletters,numbersorunderscores.Cannotuseanypunctuation,spacesarenotallowed;(2)Functionnamesarecase-sensitive;(3)Functionnamescannotusereservedwords.3.functionformandrealparametersThenameoftheparameterinthefunctionis'formalparameter',Thevaluepassedwhenthefunctioniscalledisa'realparameter'.KnowledgePoints[Definitionandinvocationoffunctions]知识点【函数的定义和调用】3.函数形参和实参函数定义时的参数名称为‘形参’,调用函数时传递的值为‘实参’。观察2:调用函数fun()前后k的值的变化观察1:形参和实参形参:a实参:k没有任何变化!!!3.functionformandrealparametersThenameoftheparameterwhendefiningthefunctionis'formalparameter',andthevaluepassedwhencallingthefunctionis'realparameter'.Observe2:Changeofkvaluebeforeandaftercallingfunctionfun()Observation1:FormalandrealparametersFormalparameter:aActualparameter:kNothinghaschanged!!!!KnowledgePoints[Definitionandinvocationoffunctions]提问【函数的定义和调用】问题1:

关于函数名,下列说法正确的是()A.函数名必须以下划线和数字开头B.函数名可以包含任意字母、数字或下划线的组合C.函数名能使用任何的标点符号D.函数名不区分大小写问题2:

说出函数形参和实参的区别。Askaquestion[Definitionandinvocationoffunctions]Question1:Regardingfunctionnames,thefollowingstatementsarecorrect()A.FunctionnamesmuststartwithanunderscoreandanumberB.Thefunctionnamecancontainanycombinationofletters,numbers,orunderscoresC.FunctionnamescanuseanypunctuationD.FunctionnamesarenotcasesensitiveQuestion2:Namethedifferencebetweenformalandrealparametersofafunction.Python语言程序设计【函数参数】PythonLanguageProgramming[FunctionParameters]知识点【函数参数】函数的参数分类:1.必需参数2.默认参数3.关键字参数4.不定长参数5.匿名函数中的参数KnowledgePoints[FunctionArguments]Classificationofargumentstofunctions:1.Requiredparameters2.Defaultparameters3.Keywordparameters4.Indefinitelengthparameters5.Parametersinanonymousfunctions知识点【函数参数】1.必需参数指的是函数要求传入的参数,调用时必须以正确的顺序传入,并且调用时的数量必须和声明时一致,否则会出现语法错误。【例】带必需参数的函数sayHello1234567defsayHello(name):

print("Hello!"+name)

return

#调用sayHello函数

sayHello("DerisWeng")

sayHello()调用sayHello(“DerisWeng”)Hello!DerisWeng调用sayHello()报错!!![FunctionArguments]1.Requiredparametersreferstothefunctionrequiredtopassparameters,thecallmustbepassedinthecorrectorder,andthenumberofcallsmustbeconsistentwiththedeclaration,otherwisetherewillbesyntaxerrors.[Example]SayHellofunctionwithrequiredparameters1234567defsayHello(name):

print("Hello!"+name)

return

#CallthesayHellofunction

sayHello("DerisWeng")

sayHello()CallsayHello("DerisWeng")Hello!DerisWengCallsayHello()ErrorReporting!!!!KnowledgePoints知识点【函数参数】2.默认参数指的是当函数中的参数设置了默认值,在调用函数时,如果没有给该参数传递任何值,则函数将会使用默认值。【例】带默认参数的函数sayHello1234567defsayHello(name,times=1):

print(("Hello!"+name)*times)

return

#调用sayHello函数

sayHello("DerisWeng")

sayHello("DerisWeng",3)调用sayHello(“DerisWeng”)Hello!DerisWeng调用sayHello(“DerisWeng”,3)Hello!DerisWengHello!DerisWengHello!DerisWeng[FunctionArguments]2.thedefaultparametersmeansthatwhenadefaultvalueissetforaparameterinafunction,thefunctionwillusethedefaultvalueifnovalueispassedtotheparameterwhenthefunctioniscalled.[Example]ThefunctionsayHellowithdefaultparameters1234567defsayHello(name,times=1):

print(("Hello!"+name)*times)

return

#CallthesayHellofunction

sayHello("DerisWeng")

sayHello("DerisWeng",3)CallsayHello("DerisWeng")Hello!DerisWengCallsayHello("DerisWeng",3)Hello!DerisWengHello!DerisWengHello!DerisWengKnowledgePoints知识点【函数参数】2.默认参数在声明函数形参时,先声明没有默认值的形参,然后再声明有默认值的形参。即默认值必须在非默认参数之后。上面这么定义是不允许的。123defsayHello(times=1,name):

print(("Hello!"+name)*times)

return是否正确?[FunctionArguments]Whendeclaringafunction'sformalparameter,firstdeclaretheformalparameterwithoutadefaultvalue,andthendeclaretheformalparameterwithadefaultvalue.Thatis,thedefaultvaluemustcomeafterthenon-defaultparameter.Theabovedefinitionisnotallowed.123defsayHello(times=1,name):

print(("Hello!"+name)*times)

returnIsthatcorrect?KnowledgePoints2.thedefaultparameters知识点【函数参数】3.关键字参数指的是如果某个函数有很多参数,在调用的时候通过参数名来对参数进行赋值。【例】使用关键字参数调用函数1234567defsayHello(name,times=1):

print(("Hello!"+name)*times)

return

#调用sayHello函数

sayHello(name="DerisWeng")

sayHello(times=3,name="DerisWeng")调用sayHello(name=“DerisWeng”)Hello!DerisWeng调用sayHello(times=3,name=“DerisWeng”)Hello!DerisWengHello!DerisWengHello!DerisWengKnowledgePoints[FunctionArguments]3.KeywordparametersThisreferstothefactthatifafunctionhasalotofparameters,theparameternamesareusedtoassignvaluestotheparameterswhenthefunctioniscalled.[Example]Callingafunctionwithakeywordargument1234567defsayHello(name,times=1):

print(("Hello!"+name)*times)

return

#CallthesayHellofunction

sayHello(name="DerisWeng")

sayHello(times=3,name="DerisWeng")CallsayHello(name="DerisWeng")Hello!DerisWengCallsayHello(times=3,name="DerisWeng")Hello!DerisWengHello!DerisWengHello!DerisWeng知识点【函数参数】4.不定长参数指的是函数的参数可以根据需要变化个数。【例】带有不定长参数的函数sayHello123456789defsayHello(name,*vars):

print("你好:")

print(name)

forvarinvars:

print(var)

return

#调用sayHello函数

sayHello("DerisWeng")

sayHello("DerisWeng","好好学习","天天向上")调用sayHello(“DerisWeng”)你好:DerisWeng调用sayHello(“DerisWeng”,“好好学习”,“天天向上”)你好:DerisWeng好好学习天天向上KnowledgePoints[FunctionArguments]4.IndefinitelengthparametersThisreferstothefactthatthenumberofargumentstoafunctioncanbevariedasneeded.[Example]SayHellofunctionwithvariablelengthparameter123456789defsayHello(name,*vars):

Print("Hello:")

print(name)

forvarinvars:

print(var)

return

#CallthesayHellofunction

sayHello("DerisWeng")

SayHello("DerisWeng","Studyhard","Makeprogresseveryday")CallsayHello("DerisWeng")HelloDerisWengCallsayHello("DerisWeng","goodgoodstudy","daydayup")Hello.DerisWenggoodgoodstudyDaybyday知识点【函数参数】5.匿名函数中的参数匿名函数指的是不用def关键字对函数进行定义,直接使用lambda来创建函数。。【例】利用lambda创建sum函数1234sum=lambdaa,b:a+b

#调用sum函数

print(sum(5,10))调用print(sum(5,10))15KnowledgePoints[FunctionArguments]5.parametersinanonymousfunctionsAnonymousfunctionreferstotheuseoflambdatocreateafunctionwithoutdefiningthefunctionwiththedefkeyword[Example]Uselambdatocreatesumfunction1234sum=lambdaa,b:a+b

#Callthesumfunction

print(sum(5,10))Callprint(sum(5,10))15知识点【函数参数】5.匿名函数中的参数匿名函数指的是不用def关键字对函数进行定义,直接使用lambda来创建函数。【例】利用lambda创建sayHello函数1234sayHello=lambdaname,times:print((“Hello!"+name)*times)

#调用sum函数sayHello("Derisweng",2)Hello!DeriswengHello!Derisweng[FunctionArguments]5.parametersinanonymousfunctionsAnonymousfunctionsrefertotheuseoflambdatocreatefunctionswithoutusingthedefkeywordtodefinethem.[Example]CreatesayHellofunctionwithlambda1234sayHello=lambdaname,times:print((“Hello!"+name)*times)

#CallthesumfunctionsayHello("Derisweng",2)Hello!DeriswengHello!DeriswengKnowledgePoints提问【函数参数】问题:

以下程序输出结果为?

deffun(x,y):

x=x+y

y=x-y

x=x-y

print(x,y)

x=2

y=3

fun(x,y)

print(x,y)Askaquestion[FunctionArguments]Question:Theoutputofthefollowingprogramis?deffun(x,y):

x=x+y

y=x-y

x=x-y

print(x,y)

x=2

y=3

fun(x,y)

print(x,y)Python语言程序设计【return语句】PythonLanguageProgramming[returnstatement]知识点【return语句】return语句用来返回函数的结果或者退出函数。【例】return不为None的情况123456defsum(a,b):

returna+b

#调用sum函数

total=sum(5,10)

print(total)不带参数值的return语句返回None,带参数值的return语句返回的就是参数的值。15输出结果:KnowledgePoints[returnstatement]returnstatementUsedtoreturntheresultofafunctionortoexitafunction.[Example]IfreturnisnotNone123456defsum(a,b):

returna+b

#Callthesumfunction

total=sum(5,10)

print(total)ThereturnstatementwithoutparametervaluereturnsNone,andthereturnstatementwithparametervaluereturnstheparametervalue.15Outputresult:知识点【return语句】return语句用来返回函数的结果或者退出函数。【例】return为None的情况123defsayHello(name):

print("Hello!"+name)

return#此处return可以不用写函数并非一定要包含return语句。如果函数没有包含return语句,Python将认为该函数返回的是None,即returnNone。None表示没有任何东西的特殊类型。KnowledgePoints[returnstatement][Example]WhenreturnisNone123defsayHello(name):

print("Hello!"+name)

Return#NoneedtowritereturnhereThefunctiondoesnothavetocontainareturnstatement.Ifthefunctiondoesnotcontainareturnstatement,PythonwillassumethatthefunctionreturnsNone,thatis,returnNone.Noneindicatesaspecialtypewithoutanything.returnstatementUsedtoreturntheresultofafunctionortoexitafunction.提问【return语句】问题:

如何让函数向调用者返回一个值?AskaquestionQuestion:HowcanImakeafunctionreturnavaluetothecaller?[returnstatement]Python语言程序设计【全局变量与局部变量】PythonLanguageProgramming[GlobalandLocalVariables]知识点【全局变量与局部变量】局部变量指在函数定义内声明的变量。【例】函数内为局部变量1234567defsum(a,b):

total=a+b#total在这里是局部变量.

print("函数内是局部变量:",total)

returntotal

#调用sum函数

sum(5,10)它们与函数外(即便是具有相同的名称)的其他变量没有任何关系。即变量的作用域只在函数的内部。函数内是局部变量:15输出结果:KnowledgePoints[GlobalandLocalVariables]localvariablesReferstoavariabledeclaredwithinafunctiondefinition.[Example]Alocalvariableinsideafunction1234567defsum(a,b):

Total=a+b#totalisalocalvariablehere

Print("Localvariableinfunction:",total)

returntotal

#Callthesumfunction

sum(5,10)Theyhavenothingtodowithothervariablesoutsidethefunction(eveniftheyhavethesamename).Thatis,thevariablesarescopedonlyinsidethefunction.Functionsarelocalizedwithinfunctions:15Outputresult:知识点【全局变量与局部变量】全局变量在函数外部声明的变量称为全局变量,程序中的任何地方都可以读取它。【例】利用global实现函数内访问全局变量12345678defshowName():

globalname

print("你的姓名:"+name)

name="Weng"

#调用showName函数

name="Deris"

showName()

print(("你现在的姓名:"+name))如果需要在函数内部访问全局变量,一般要用到global关键字。你的姓名:Deris你现在的姓名:Weng输出结果:globalvariablesAvariabledeclaredoutsideafunctioniscalledaglobalvariableandcanbereadanywhereintheprogram.[Example]Usingglobaltoaccessglobalvariableswithinafunction12345678defshowName():

globalname

Print("Yourname:"+name)

name="Weng"

#CalltheshowNamefunction

name="Deris"

showName()

Print(("Yourcurrentname:"+name))Ifyouneedtoaccessglobalvariableswithinafunction,yougenerallyneedtousetheglobalkeyword.Yourname:DerisYourcurrentname:WengKnowledgePoints[GlobalandLocalVariables]Outputresult:知识点【全局变量与局部变量】全局变量【例】没有用global的情况下,无法在函数内部修改全局变量。123456789name="Deris"

defsayHello():

print("hello"+name+"!")

defchangeName(newName):

name=newName

#调用函数

sayHello()

changeName("Weng")

sayHello()helloDeris!helloDeris!输出结果:globalvariables[Example]Whenglobalisnotused,globalvariablescannotbemodifiedinsidethefunction.123456789name="Deris"

defsayHello():

print("hello"+name+"!")

defchangeName(newName):

name=newName

#Callingfunctions

sayHello()

changeName("Weng")

sayHello()helloDeris!helloDeris!KnowledgePoints[GlobalandLocalVariables]Outputresult:知识点【全局变量与局部变量】全局变量【例】用global在函数内部修改全局变量。12345678910name="Deris"

defsayHello():

print("hello"+name+"!")

defchangeName(newName):

globalname

name=newName

#调用函数

sayHello()

changeName("Weng")

sayHello()helloDeris!helloWeng!输出结果:globalvariables[Example]Useglobaltomodifyglobalvariableswithinafunction.12345678910name="Deris"

defsayHello():

print("hello"+name+"!")

defchangeName(newName):

globalname

name=newName

#Callingfunctions

sayHello()

changeName("Weng")

sayHello()helloDeris!helloWeng!KnowledgePoints[GlobalandLocalVariables]Outputresult:提问【全局变量与局部变量】问题:全局变量与局部变量有什么区别?Askaquestion[GlobalandLocalVariables]Question:Whatisthedifferencebetweenaglobalvariableandalocalvariable?Python语言程序设计【函数作用域+模块+缩进格式】PythonLanguageProgramming[DocumentString+FormattedOutput+Built-inFunctions]知识点【函数作用域】变量的作用域指的是变量在程序中的哪些地方可以访问或者可见。1.每个模块都有自已的全局作用域。2.函数定义的对象属局部作用域,只在函数内有效,不会影响全局作用域中的对象。3.赋值对象属局部作用域,除非使用global关键字进行声明。12345678910name="Deris"

defsayHello():

print("hello"+name+"!")

defchangeName(newName):

globalname

name=newName

#调用函数

sayHello()

changeName("Weng")

sayHello()KnowledgePoints[FunctionScope]thescopeofthevariablereferstowhereintheprogramthevariableisaccessibleorvisible.1.eachmodulehasitsownglobalscope.2.functiondefinitionoftheobjectisalocalscope,onlyinthefunctionisvalid,willnotaffecttheglobalscopeoftheobject.3.Theassignmentobjectislocallyscopedunlessdeclaredwiththeglobalkeyword.12345678910name="Deris"

defsayHello():

print("hello"+name+"!")

defchangeName(newName):

globalname

name=newName

#Callingfunctions

sayHello()

changeName("Weng")

sayHello()课后练习【函数作用域】问题:课后请查阅一下什么是LEGB规则?After-schoolexercises[FunctionScope]Question:WhatareLEGBrulesafterclass?知识点【模块】模块一个包含所有定义的函数和变量的文件,模块必须以.py为后缀名。pythonhello.py这是“hello.py”模块hello12345678#hello.py

defsayHello():

str="hello"

print(str)

if__name__=="__main__":

print("这是hello.py模块")

sayHello()模块可以从其他程序中引入(import),引入后就可以用模块中的函数和功能,从而达到代码复用的作用。>>>importhello>>>hello.__name__'hello'KnowledgePoints[Module]ModuleAfilecontainingalldefinedfunctionsandvariables.Themodulemusthavethesuffix.py.pythonhello.pyThisisthe"hello.py"modulehello12345678#hello.py

defsayHello():

str="hello"

print(str)

if__name__=="__main__":

Print("Thisisthehello.pymodule")

sayHello()Modulescanbeimportedfromotherprograms,andthenthefunctionsandfunctionsinthemodulecanbeusedtoachievecodereuse.>>>importhello>>>hello.__name__'hello'课后练习【模块】问题:模块的__name__的作用和用法?After-schoolexercises[Module]Question:Whatisthefunctionandusageofthe__name__ofthemodule?知识点【编程缩进格式】缩进指在代码行开始部分的空格。123456defsum(a,b):

returna+b

#调用sum函数

total=sum(5,10)

print(total)代码行开头的前导空白用于确定语句的分组,同样的缩进级别的语句属于同一语句块。(四个空格)或Tab(不建议使用)KnowledgePoints[ProgrammingIndentFormat]Indentreferstoaspaceatthebeginningofalineofcode.123456defsum(a,b):

returna+b

#Callthesumfunction

total=sum(5,10)

print(total)Leadingwhitespaceatthebeginningofalineofcodeisusedtodeterminethegroupingofstatementswiththesamelevelofindentationintothesamestatementblock.(fourspaces)orTab(notrecommended)知识点【编程缩进格式】缩进的错误用法!运行这段程序的结果如下:File"例1-3.py",line2print('IamPython');^ndentationError:unexpectedindent12print('Hello,')

print('IamPython')#注意此处特地在前面留了一个空格KnowledgePoints[ProgrammingIndentFormat]Wronguseofindentation!Theresultofrunningthisprogramisasfollows.File"Example1-3.py",line2print('IamPython');^ndentationError:unexpectedindent12print('Hello,')

Print('IamPython')#Notethataspaceisspeciallyleftinfront课后练习【编程缩进格式】问题:平级的语句行(代码块)的缩进可以不同吗?After-schoolexercises[ProgrammingIndentFormat]Question:Cantheindentationofleveledstatementlines(codeblocks)bedifferent?Python语言程序设计【文档字符串+格式化输出+内置函数】PythonLanguageProgramming[DocumentString+FormattedOutput+Built-inFunctions]知识点【文档字符串】文档字符串Python用三个引号标识文档字符串的开始和结尾。123456importmath

defarea(radius):

"""

returntheareaofcircle

"""

returnmath.pi*

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论