函数
函数的创建和调用
>>> def MyFirstFunction():
print('hello world')
print('this is my first function')
>>> MyFirstFunction()
hello world
this 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 + num2
return 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的参数可以有多个,但不建议过多,不便于维护。
函数,对象,模块