【Python操作基础】——函数

🍉CSDN小墨&晓末:https://blog.csdn.net/jd1813346972

   个人介绍: 研一|统计学|干货分享
         擅长Python、Matlab、R等主流编程软件
         累计十余项国家级比赛奖项,参与研究经费10w、40w级横向

【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
  • 62
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值