【Python】学习Python常用函数作用和用法

简介: 【Python】学习Python常用函数作用和用法
1.函数

函数就是把程序进行打包,封装到一个包中,使用时可以直接进行调用

1.创建函数和调用函数:
>>> def test():
  pass
>>> test()
>>> def test():
  for i in range(3):
    print("I love curry")
调用函数
>>> test
<function test at 0x000001B617CCF3A0>
>>> test()
I love curry
I love curry
I love curry
2.创建传参函数
>>> def test(times,name):
  for i in range(times):
    print(f"I love {name}")
>>> test(5,"Python")
I love Python
I love Python
I love Python
I love Python
I love Python
3.函数的返回值

return:直接返回值,不在理会后面的所有的代码

>>> def test(x,y):
  return x/y
>>> test(4,2)
2.0
>>> def test(x,y):
  if y == 0:
    return "不能为0"
  return x/y
>>> test(10,2)
5.0
4.位置参数

在使用传参函数中有两种关键称呼:

形式参数(形参):在创建函数时,预留的变量名被称为形参

实际参数(实参):在调用函数时,给于的参数被称为实参

>>> def test(a,b,c):
  return "".join((c,b,a))
位置参数传参
>>> test("我","爱","你")
'你爱我'
关键参数传参
>>> test(c="我",b="爱",a="你")
'我爱你'

默认参数:

>>> def test(a,b,c="她"):
  return "".join((c,b,a))
>>> test("我","爱")
'她爱我'
5.冷知识
>>> help(sum)
Help on built-in function sum in module builtins:
sum(iterable, /, start=0)
    Return the sum of a 'start' value (default: 0) plus an iterable of numbers
    When the iterable is empty, return the start value.
    This function is intended specifically for use with numeric values and may
    reject non-numeric types.

可以看到,使用格式中出现了一个 / 反斜杠,他是代表在它之前是不允许使用关键字参数的,只可以使用位置参数

在函数中也一样,但是我们可以使用*星号来代替,这样第一位可以为位置参数或关键参数,但是后面都要为关键字参数

>>> def test(a,*,b,c):
  return "".join((c,b,a))
>>> test(a="我",b="爱",c="她")
'她爱我'
>>> test("我",b="爱",c="她")
'她爱我'
>>> test("我","爱","她")
Traceback (most recent call last):
  File "<pyshell#181>", line 1, in <module>
    test("我","爱","她")
TypeError: test() takes 1 positional argument but 3 were given
6.多参参数

传入多个参数,是以元组的形式来进行打包的,只需要在变量名前面多加一个*星号即可

第二种理解:传入一个元组类型的变量,将多个值放到一个元组中

>>> def test(*args):
  print(f"一共多少个参数{len(args)}")
  print(f"第2个参数是什么:{args[1]}")
>>> test(1,2,3,4,5)
一共多少个参数5
第2个参数是什么:2

如果使用了多参赋值,后面的其他变量,必须使用关键字参数来进行赋值了

>>> def test(*args,a,b):
  print(args,a,b)
>>> test(1,2,3,4,5,a=6,b=7)
(1, 2, 3, 4, 5) 6 7
字典函数

在声明一个函数中,可以同时声明一个字典类型的变量来存储数据

>>> def test(**args):
  print(args)
>>> test(a=1,b=2,c=3)
{'a': 1, 'b': 2, 'c': 3}
>>> def test(a,*b,**args):
  print(a,b,args)
>>> test(1,2,3,4,5,d=1,b=2,c=3)
1 (2, 3, 4, 5) {'d': 1, 'b': 2, 'c': 3}
解包参数

元组的解包

>>> args=(1,2,3,4)
>>> def test(a,b,c,d):
  print(a,b,c,d)
>>> test(*args)
1 2 3 4

字典的解包

>>> args={'a':1,'b':2,'c':3,'d':4}
>>> test(**args)
1 2 3 4
7.作用域
1.局部作用域
>>> def test():
  x=520
  return x
>>> test()
520
>>> print (x)
Traceback (most recent call last):
  File "<pyshell#266>", line 1, in <module>
    print (x)
NameError: name 'x' is not defined
2.全局作用域
>>> x = 888
>>> def test():
  return x
>>> test()
888

如果在函数的局部变量中与全局变量的名称相同,那么局部变量会代替全局变量,仅限于在当前函数中使用

>>> x = 888
>>> def test():
  return x
>>> test()
888
>>> def test():
  x = 666
  return x
>>> test()
666
3.global语句

使用global来进行声明变量为全局变量

>>> x = 888
>>> def test():
  global x
  x = 520
  return x
>>> x
888
>>> test()
520
>>> x
520
4.嵌套函数
>>> def funA():
  x = 520
  def funB():
    x = 666
    print (f"FunB:{x}")
  funB()
  return f"funA:{x}"
>>> funA()
FunB:666
'funA:520'
5.nonlocal语句

作用:可以将变量申明为外部变量

>>> def funA():
  x = 520
  def funB():
    nonlocal x
    x = 666
    print (f"FunB:{x}")
  funB()
  return f"funA:{x}"
>>> funA()
FunB:666
'funA:666'
6.LEGB规则

L:local(局部作用域)E:enclosed(嵌套函数的外层函数作用域)G:global(全局作用域)B:build-ln(内置作用yu)

当一个局部变量与全局变量相同时,这个局部变量就会代替全局变量来进行被调用使用

>>> str(123)
'123'
>>> str="123"
>>> str(123)
Traceback (most recent call last):
  File "<pyshell#313>", line 1, in <module>
    str(123)
TypeError: 'str' object is not callable
>>> del str
>>> str(123)
'123'

注意:为了避免这种情况发生,在声明变量时,尽量不要出现与python中的内置函数名冲突

1,2,3,4,5,a=6,b=7)

(1, 2, 3, 4, 5) 6 7

######  字典函数
    在声明一个函数中,可以同时声明一个字典类型的变量来存储数据
```py
>>> def test(**args):
  print(args)
>>> test(a=1,b=2,c=3)
{'a': 1, 'b': 2, 'c': 3}
>>> def test(a,*b,**args):
  print(a,b,args)
>>> test(1,2,3,4,5,d=1,b=2,c=3)
1 (2, 3, 4, 5) {'d': 1, 'b': 2, 'c': 3}
解包参数

元组的解包

>>> args=(1,2,3,4)
>>> def test(a,b,c,d):
  print(a,b,c,d)
>>> test(*args)
1 2 3 4

字典的解包

>>> args={'a':1,'b':2,'c':3,'d':4}
>>> test(**args)
1 2 3 4
7.作用域
1.局部作用域
>>> def test():
  x=520
  return x
>>> test()
520
>>> print (x)
Traceback (most recent call last):
  File "<pyshell#266>", line 1, in <module>
    print (x)
NameError: name 'x' is not defined
2.全局作用域
>>> x = 888
>>> def test():
  return x
>>> test()
888

如果在函数的局部变量中与全局变量的名称相同,那么局部变量会代替全局变量,仅限于在当前函数中使用

>>> x = 888
>>> def test():
  return x
>>> test()
888
>>> def test():
  x = 666
  return x
>>> test()
666
3.global语句

使用global来进行声明变量为全局变量

>>> x = 888
>>> def test():
  global x
  x = 520
  return x
>>> x
888
>>> test()
520
>>> x
520
4.嵌套函数
>>> def funA():
  x = 520
  def funB():
    x = 666
    print (f"FunB:{x}")
  funB()
  return f"funA:{x}"
>>> funA()
FunB:666
'funA:520'
5.nonlocal语句

作用:可以将变量申明为外部变量

>>> def funA():
  x = 520
  def funB():
    nonlocal x
    x = 666
    print (f"FunB:{x}")
  funB()
  return f"funA:{x}"
>>> funA()
FunB:666
'funA:666'
6.LEGB规则

L:local(局部作用域)E:enclosed(嵌套函数的外层函数作用域)G:global(全局作用域)B:build-ln(内置作用yu)

当一个局部变量与全局变量相同时,这个局部变量就会代替全局变量来进行被调用使用

>>> str(123)
'123'
>>> str="123"
>>> str(123)
Traceback (most recent call last):
  File "<pyshell#313>", line 1, in <module>
    str(123)
TypeError: 'str' object is not callable
>>> del str
>>> str(123)
'123'

注意:为了避免这种情况发生,在声明变量时,尽量不要出现与python中的内置函数名冲突

目录
相关文章
|
2天前
|
Python
Python闭包函数和计时器
本文介绍了闭包函数的概念,它允许内部函数引用外部作用域的变量但无法修改它们。示例展示了如何使用闭包来封装函数。接着,文章讨论了如何在函数调用时添加开始和结束的打印语句,通过传递函数作为参数实现。然后,文章引入装饰器,通过闭包定义了一个`timer`装饰器,用于在函数执行前后打印消息。最后,给出了一个练习,实现了一个计算函数执行时间的装饰器,处理了带有参数的被装饰函数。
12 1
|
1天前
|
机器学习/深度学习 数据采集 自然语言处理
python函数参数的传递、带星号参数的传递,2024年大厂Python高级面试题分享
python函数参数的传递、带星号参数的传递,2024年大厂Python高级面试题分享
|
1天前
|
Python
Python 使用type()函数
【5月更文挑战第10天】
11 4
|
1天前
|
Python
Python使用isinstance()函数
【5月更文挑战第10天】Python使用isinstance()函数
9 2
|
1天前
|
缓存 Python
Python中的装饰器:优雅而强大的函数装饰技术
在Python编程中,装饰器是一种强大而灵活的技术,它可以使函数具有额外的功能,而不需要改变函数的核心代码。本文将深入探讨装饰器的原理、用法以及实际应用场景,帮助读者更好地理解和利用这一重要的Python编程工具。
|
2天前
|
Python
PyQt学习------PyQt自定义信号
PyQt学习------PyQt自定义信号
11 0
|
2天前
|
Python
PyQt---------信号与槽函数的关系
PyQt---------信号与槽函数的关系
11 1
|
2天前
|
图形学 Python
pyqt的学习(三)----鼠标点击和按键处理
pyqt的学习(三)----鼠标点击和按键处理
10 1
|
2天前
|
NoSQL 数据库 Python
PyQt学习(二)-----图形的建立(柱状图,折线图,堆叠柱状图,饼图)
PyQt学习(二)-----图形的建立(柱状图,折线图,堆叠柱状图,饼图)
7 1
|
2天前
|
C++ 计算机视觉 Python
【学习什锦】python中的匿名函数(lambda)与max、key参数
【学习什锦】python中的匿名函数(lambda)与max、key参数
10 3