Python-13 函数,Python的乐高积木

来源:互联网 发布:gif快手刷粉丝软件 编辑:程序博客网 时间:2024/04/28 23:55

函数 

函数的创建和调用

>>> def MyFirstFunction():print('hello world')print('this is my first function')>>> MyFirstFunction()hello worldthis is my first function>>> 


如果调用没有定义的函数名

>>> MySecondFunction()Traceback (most recent call last):  File "<pyshell#5>", line 1, in <module>    MySecondFunction()NameError: name 'MySecondFunction' is not defined>>> 

函数中增加参数

>>> def MySecondFunction(name):print('Hi '+name)>>> MySecondFunction()Traceback (most recent call last):  File "<pyshell#9>", line 1, in <module>    MySecondFunction()TypeError: MySecondFunction() missing 1 required positional argument: 'name'>>> MySecondFunction('Ethan')Hi Ethan>>> 


函数增加return

>>> def MyThirdFunction(num1,num2):result = num1 + num2return result>>> MyThirdFunction()Traceback (most recent call last):  File "<pyshell#15>", line 1, in <module>    MyThirdFunction()TypeError: MyThirdFunction() missing 2 required positional arguments: 'num1' and 'num2'>>> MyThirdFunction(3,5)8>>> 

>>> print(MyThirdFunction(3,5))8>>> 




python的参数可以有多个,但不建议过多,不便于维护。


函数,对象,模块






原创粉丝点击