Python入门(五)之 Python函数
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Python入门(五)之 Python函数,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含6477字,纯文字阅读大概需要10分钟。
内容图文
![Python入门(五)之 Python函数](/upload/InfoBanner/zyjiaocheng/639/a9adb533490b470e87f7a8a09d0def69.jpg)
作者:PyQuant
博客:https://blog.csdn.net/qq_33499889
慕课:https://mooc1-2.chaoxing.com/course/207443619.html
点赞、关注再看,养成良好习惯
Life is short, U need Python
初学Python,快来点我吧
1. 函数的基本结构
2. 函数的定义
def hello():
print('hello python!')
hello()
hello python!
def foo(a,b):
c = a + b
return c
r = foo(10,20)
print(r)
30
3. 函数的参数
函数的参数类型一般分为如下四种形式:
-
必需参数
-
关键字参数
-
默认参数
-
不定长参数
【1】必须参数
-
必需参数须以正确的顺序传入函数。
-
调用时的数量必须和声明时的一样,不然会出现语法错误。
-
实例:
def myprint(my_string):
print(my_string)
myprint('hello python')
hello python
【2】关键字参数
-
关键字参数和函数调用关系紧密,函数调用使用关键字参数来确定传入的参数值。
-
使用关键字参数允许函数调用时参数的顺序与声明时不一致,因为 Python 解释器能够用参数名匹配参数值。
-
实例:
def print_me(name, age):
print ("名字: ", name)
print ("年龄: ", age)
return
print_me("PyQuant", 30 )
名字: PyQuant
年龄: 30
print_me(age=30, name="PyQuant" )
名字: PyQuant
年龄: 30
【3】默认参数
-
调用函数时,如果没有传递参数,则会使用默认参数。以下实例中如果没有传入 age 参数,则使用默认值。
-
实例:
def print_me(name, age=30):
print ("姓名-->", name)
print ("年龄-->", age)
return
print_me("PyQuant" )
姓名--> PyQuant
年龄--> 30
print_me("PyQuant" ,40)
姓名--> PyQuant
年龄--> 40
【4】不定长参数
- 你可能需要一个函数能处理比当初声明时更多的参数。这些参数叫做不定长参数,和上述参数不同,声明时不会命名。
- 实例
def print_me(arg, *args):
print('arg -->', arg)
print('*args -->', args)
print_me(30,2,3,4)
arg --> 30
*args --> (2, 3, 4)
def print_me(arg, **args):
print('arg -->', arg)
print('**args -->', args)
print_me(30,a=2,b=3,c=4)
arg --> 30
**args --> {'a': 2, 'b': 3, 'c': 4}
4. 特殊函数
-
lambda函数
-
map()函数
-
filter()函数
【1】lambda
Python 使用 lambda 来创建匿名函数,不再使用 def 语句这样标准的形式定义一个函数。
-
lambda 只是一个表达式,函数体比 def 简单很多。
-
lambda的主体是一个表达式,而不是一个代码块。仅仅能在lambda表达式中封装有限的逻辑进去。
-
lambda 函数拥有自己的命名空间,且不能访问自己参数列表之外或全局命名空间里的参数。
polynomial = lambda x,y: x**2 + y**2
polynomial(1,2)
5
【2】map()
map() 函数会根据提供的函数对指定序列做映射。
其语法形式为:map(function, iterable, …):
-
function ---- 以参数序列中的每一个元素调用 function 函数。
-
iterable ---- 一个或多个序列(比如:列表、元组和字典等)。
-
返回值 ---- Python 3.x 返回迭代器,通过序列的内置函数(比如: list,tuple,set等)进行显示。
lst = [1,2,3]
m = map(lambda x: 10*x ,lst)
m
<map at 0x1c93abb7208>
list(m)
[10, 20, 30]
def f(x,y):
return (x,y)
lst_1 = [0,1,2,3,4,5,6]
lst_2 = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat']
print(list(map(f,lst_1,lst_2)))
[(0, 'Sun'), (1, 'Mon'), (2, 'Tue'), (3, 'Wed'), (4, 'Thu'), (5, 'Fri'), (6, 'Sat')]
【3】filter()
filter() 函数用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的新列表。
其语法形式为:filter(function, iterable)
-
function ---- 判断函数。
-
iterable ---- 可迭代对象。
-
返回值 ---- Python 3.x 返回迭代器。
numbers = range(-3,3)
f = filter(lambda x: x > 0, numbers)
f
<filter at 0x1c93ab05b70>
list(f)
[1, 2]
5. 作用域
-
局部作用域(Local)
-
全局作用域(Global)
-
嵌套作用域(Enclosing)
-
内置作用域(builtin)
【1】局部作用域(Local)
a = 100
def func():
a = 300
print('局部作用域: ', a)
func()
局部作用域: 300
【2】全局作用域(Global)
a = 100
def func():
a = 300
print('局部作用域: ', a)
func()
print('全局作用域: ', a)
局部作用域: 300
全局作用域: 100
a = 100
def func():
a += 100
print('局部作用域: ', a)
func()
print('全局作用域: ', a)
---------------------------------------------------------------------------
UnboundLocalError Traceback (most recent call last)
<ipython-input-41-4c68dbc3afd0> in <module>()
3 a += 100
4 print('局部作用域: ', a)
----> 5 func()
6 print('全局作用域: ', a)
<ipython-input-41-4c68dbc3afd0> in func()
1 a = 100
2 def func():
----> 3 a += 100
4 print('局部作用域: ', a)
5 func()
UnboundLocalError: local variable 'a' referenced before assignment
a = 100
def func():
global a
a += 100
print('局部作用域: ', a)
func()
print('全局作用域: ', a)
局部作用域: 200
全局作用域: 200
【3】嵌套作用域(Enclosing)----> 嵌套函数
x = 123
def f1():
x = 100
print('f1--->',x)
def f2():
x = 200
print('f2--->',x)
f2()
f1()
f1---> 100
f2---> 200
【4】内置作用域(builtin)
import builtins
print(dir(builtins))
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '__IPYTHON__', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'display', 'divmod', 'enumerate', 'eval', 'exec', 'filter', 'float', 'format', 'frozenset', 'get_ipython', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
- 写作不易,切勿白剽
- 博友们的点赞和关注就是对博主坚持写作的最大鼓励
- 持续更新,未完待续…
上一篇:Python入门(四)之 循环语句—解析式
下一篇:Python入门(六)之 Python “ 三器 ”
内容总结
以上是互联网集市为您收集整理的Python入门(五)之 Python函数全部内容,希望文章能够帮你解决Python入门(五)之 Python函数所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。