【Python操作基础】——函数

简介: 【Python操作基础】——函数

【Python操作基础】系列——函数操作,建议收藏!

该篇文章首先利用Python展示了使用函数的相关操作,包括内置函数、模块函数、用户自定义函数、lambda函数等。

1 内置函数

1.1 简单示例

  运行程序:

i=20
type(i)

  运行结果:

int

1.2 内置函数的主要特点

  运行程序:

i=20
type(20)
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',
 'breakpoint',
 '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']

1.3 数学函数

  运行程序:

abs(-1)
min([1,2,3])
max([1,2,3])
pow(2,10)
round(2.991,2)

  运行结果:

1
1
3
1024
2.99

1.4 类型函数

  运行程序:

int(1.134)
bool(1)
float(1)
str(123)
list("chao")
set("chao")
tuple("chao")

  运行结果:

1
True
1.0
'123'
['c', 'h', 'a', 'o']
{'a', 'c', 'h', 'o'}
('c', 'h', 'a', 'o')

1.5 其他功能函数

  运行程序:

i=0
type(i)
isinstance(i, int) #判断函数类型
dir() #查看搜索路径
myList=[1,2,3,4,5]
len(myList)
range(1,10,2)
list(range(1,10,2))
callable(dir)#判断函数是否可调用
bin(8) #十进制转换为二进制
hex(8) #十进制转换为十六进制

  运行结果:

int
True
['In',
 'InteractiveShell',
 'NamespaceMagics',
 'Out',
 '_',
 '_1',
 '_10',
 '_11',
 '_12',
 '_13',
 '_14',
 '_15',
 '_16',
 '_18',
 '_19',
 '_2',
 '_20',
 '_21',
 '_23',
 '_24',
 '_25',
 '_26',
 '_27',
 '_29',
 '_3',
 '_30',
 '_31',
 '_36',
 '_37',
 '_39',
 '_4',
 '_40',
 '_41',
 '_42',
 '_43',
 '_44',
 '_45',
 '_48',
 '_49',
 '_5',
 '_50',
 '_52',
 '_53',
 '_54',
 '_55',
 '_56',
 '_57',
 '_6',
 '_7',
 '_8',
 '_9',
 '_Jupyter',
 '__',
 '___',
 '__builtin__',
 '__builtins__',
 '__doc__',
 '__loader__',
 '__name__',
 '__package__',
 '__spec__',
 '_dh',
 '_getshapeof',
 '_getsizeof',
 '_i',
 '_i1',
 '_i10',
 '_i11',
 '_i12',
 '_i13',
 '_i14',
 '_i15',
 '_i16',
 '_i17',
 '_i18',
 '_i19',
 '_i2',
 '_i20',
 '_i21',
 '_i22',
 '_i23',
 '_i24',
 '_i25',
 '_i26',
 '_i27',
 '_i28',
 '_i29',
 '_i3',
 '_i30',
 '_i31',
 '_i32',
 '_i33',
 '_i34',
 '_i35',
 '_i36',
 '_i37',
 '_i38',
 '_i39',
 '_i4',
 '_i40',
 '_i41',
 '_i42',
 '_i43',
 '_i44',
 '_i45',
 '_i46',
 '_i47',
 '_i48',
 '_i49',
 '_i5',
 '_i50',
 '_i51',
 '_i52',
 '_i53',
 '_i54',
 '_i55',
 '_i56',
 '_i57',
 '_i6',
 '_i7',
 '_i8',
 '_i9',
 '_ih',
 '_ii',
 '_iii',
 '_nms',
 '_oh',
 'a1',
 'a2',
 'a3',
 'a4',
 'a5',
 'a6',
 'a7',
 'a8',
 'a9',
 'exit',
 'func',
 'get_ipython',
 'getsizeof',
 'i',
 'json',
 'lst_1',
 'lst_2',
 'mt',
 'myDict1',
 'myDict2',
 'myFunc',
 'myGen',
 'myIterator',
 'myList',
 'myList1',
 'myList2',
 'myList3',
 'mySet1',
 'mySet10',
 'mySet11',
 'mySet2',
 'mySet3',
 'mySet4',
 'mySet5',
 'mySet6',
 'mySet7',
 'mySet8',
 'mySet9',
 'myString',
 'myTuple',
 'myTuple1',
 'myTuple2',
 'myTuple3',
 'myTuple4',
 'np',
 'p1',
 'quit',
 'r1',
 're',
 's',
 's1',
 'sep_str',
 'seq',
 'str1',
 'str2',
 'str3',
 'str4',
 'sum',
 'value',
 'var_dic_list',
 'x',
 'x1',
 'x2',
 'x3',
 'x4',
 'x5',
 'y',
 'z']
5
range(1, 10, 2)
[1, 3, 5, 7, 9]
True
'0b1000'
'0x8'

2 模块函数

2.1 简单示例

  运行程序:

import math as mt
mt.sin(1.5)

  运行结果:

0.9974949866040544

2.2 import 模块名

  运行程序:

import math
math.sin(1.5)
#cos(1.5) #报错,cos未引用模块
math.cos(1.5)

  运行结果:

0.9974949866040544
0.0707372016677029

2.2 import 模块名 as 别名

  运行程序:

import math as mt  #更改未别名
mt.sin(1.5)

  运行结果:

0.9974949866040544

2.3 from 模块名 import 函数名

  运行程序:

from math import cos#从模块中引用函数
cos(1.5) 
from math import sin
sin(1.5)

  运行结果:

0.0707372016677029
0.9974949866040544

3 用户自定义函数

3.1 简单示例

  运行程序:

def myFunc():
    j=0
    print('hello world')
myFunc()

  运行结果:

hello world

3.2 定义方法

  运行程序:

def func():
    j=0
    print('hello world')
    
    def func2(i):
        print('pass'+str(i)+str(j))
        
    return func2
func()
func()(2)

  运行结果:

hello world
<function __main__.func.<locals>.func2(i)>
hello world
pass20

3.3 函数中的docString

  运行程序:

def get_name(msg):
    name = input(msg) or 'Anonymous User'
    return name
help(get_name) 
#get_name?#报错:根据用户提示msg,获取用户名,如果输入为空,则默认未Friend

  运行结果:

File "<ipython-input-74-0273dd82ff56>", line 6
    get_name?#根据用户提示msg,获取用户名,如果输入为空,则默认未Friend
            ^
SyntaxError: invalid syntax

3.4 调用方法

  运行程序:

get_name('plz enter your name : ')
print(callable(get_name))#判断是否可调用

  运行结果:

plz enter your name : print(callable(get_name))
'print(callable(get_name))'
True

3.5 返回值

  运行程序:

def myfunc(i,j=2):
    j=i+1
    return j
print(myfunc(3))
def myfunc(i,j=2):
    j=i+1
print(myfunc(3))
def myfunc(i,j=2):
    j=i+1
    return i,j    
a,b =myfunc(3)
a,b

  运行结果:

4
None
(3, 4)

3.6 自定义函数的形参与实参

  运行程序:

def my_func(x1,*x2,x3,x5=5,x4=4):
    print(x1)
    print(x2)
    print(x3)
    print(x4)
    print(x5)
my_func(1,2,4,x3=3,x5=5)
my_func(1,2,x4=4,x3=3,x5=5)
my_func(1,2,4,x3=3,x5=5)

  运行结果:

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

3.7 变量的可见性

  运行程序:

x=0
def myFunc(i):
    x=i
    print(x)
myFunc(1)
print(x)
x=0
def myFunc(i):
    global x
    x=i 
    print(x)
myFunc(1)
print(x)
x=0
def myFunc(i):
    x=i
    def myF():
        nonlocal x
        x=2
        print(x)
    print(x)
myFunc(1)
print(x)

  运行结果:

1
0
1
1
1
0

3.8 值传递与地址传递

  运行程序:

i=100
def myfunc(j,k=2): #值传递,形参实参分别占用不同内存空间,在被调用函数中修改形参,不会改变实参值
    j+=2 
myfunc(i)
print(i)
i=[100]
def myfunc(j,k=2):
    j[0]+=2       #地址传递。形参和实参共享同一内存空间,形参发生变化,实参也随之发生变化
myfunc(i)
print(i)

  运行结果:

100
[102]

3.9 自定义函数时的注意事项

  运行程序:

def myfunc(j,k=2):#自定义函数参数分别为位置参数,关键字参数
    j+=k
    j
d=myfunc(2,3)
d
def myfunc(k=2,j):
    j+=k
    j
d=myfunc(2,3)
d#报错,关键字必须在位置参数后
def myfunc(j,k=2):
    j+=k
    j
d=myfunc(3)
print(d)#函数没有return,自动返回None
d is None
myfunc=abs
print(type(myfunc))#python认为,一切皆为对象
print(myfunc(-100))

  运行结果:

None

4 lambda函数

4.1 lambda函数的定义方法

  运行程序:

x=2
y= lambda x:x+3
y(2)
x=2
def myfunc(x):
  return x+3
myfunc(2)

  运行结果:

5
5

4.2 lambda函数的调用方法

  运行程序:

#lambda通常以另一个函数的参数形式使用
MyList = [1,2,3,4,5,6,7,8,9,10]
filter(lambda x: x % 3 == 0, MyList)
list(filter(lambda x: x % 3 == 0, MyList))
list(map(lambda x: x * 2, MyList))
from functools import reduce
reduce(lambda x, y: x + y, MyList)

  运行结果:

<filter at 0x2cd44b2d940>
[3, 6, 9]
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
55


相关文章
|
30天前
|
开发者 Python 容器
python函数基础以及函数参数简解
python函数基础以及函数参数简解
|
4天前
|
Python
[oeasy]python035_根据序号得到字符_chr函数_字符_character_
本文介绍了Python中的`ord()`和`chr()`函数。`ord()`函数通过字符找到对应的序号,而`chr()`函数则根据序号找到对应的字符。两者互为逆运算,可以相互转换。文章还探讨了单双引号在字符串中的作用,并解释了中文字符和emoji也有对应的序号。最后总结了`ord()`和`chr()`函数的特点,并提供了学习资源链接。
14 4
|
7天前
|
Java Python
全网最适合入门的面向对象编程教程:50 Python函数方法与接口-接口和抽象基类
【9月更文挑战第18天】在 Python 中,虽无明确的 `interface` 关键字,但可通过约定实现类似功能。接口主要规定了需实现的方法,不提供具体实现。抽象基类(ABC)则通过 `@abstractmethod` 装饰器定义抽象方法,子类必须实现这些方法。使用抽象基类可使继承结构更清晰、规范,并确保子类遵循指定的方法实现。然而,其使用应根据实际需求决定,避免过度设计导致代码复杂。
|
10天前
|
Python
全网最适合入门的面向对象编程教程:Python函数方法与接口-函数与方法的区别和lamda匿名函数
【9月更文挑战第15天】在 Python 中,函数与方法有所区别:函数是独立的代码块,可通过函数名直接调用,不依赖特定类或对象;方法则是与类或对象关联的函数,通常在类内部定义并通过对象调用。Lambda 函数是一种简洁的匿名函数定义方式,常用于简单的操作或作为其他函数的参数。根据需求,可选择使用函数、方法或 lambda 函数来实现代码逻辑。
|
23天前
|
Python
python 函数
【9月更文挑战第4天】python 函数
37 5
WK
|
30天前
|
Python
python中的函数有哪些种类?
在 Python 中,函数根据定义方式、用途及来源可分为多种类型:自带的内置函数(如 print(), len())无需导入直接使用;标准库函数需导入相应模块后使用;第三方库函数则需先安装库再导入使用;用户自定义函数可根据需求定义并多次调用;匿名函数(lambda)无函数名,常用于需要函数对象但不想单独定义的情形;高阶函数接受或返回函数;装饰器函数可在不改动原函数代码情况下为其添加新功能;生成器函数使用 yield 逐个返回值;递归函数在自身定义中调用自身;嵌套函数在一个函数内定义,可访问外部函数变量。各种函数类型在编程中有不同的用途和优势。
WK
41 12
|
29天前
|
Python
Python 中 help() 和 dir() 函数的用法
【8月更文挑战第29天】
24 5
|
30天前
|
Python
12类常用的Python函数
12类常用的Python函数
|
30天前
|
Python
python中getattr函数 hasattr函数
python中getattr函数 hasattr函数
|
30天前
|
算法 Python
python函数递归和生成器
python函数递归和生成器