首页 > 其他分享 >函数

函数

时间:2022-08-15 10:22:43浏览次数:36  
标签:myfunc return 函数 args funA print def

##函数

#创建和调用函数

def myfunc():
pass

myfunc()
def myfunc():
for i in range(3):
print("I love you")


myfunc()
I love you
I love you
I love you

#函数参数
def myfunc(name):
for i in range(3):
print(f"I love {name}.")


myfunc("huibao")
I love huibao.
I love huibao.
I love huibao.

##函数的返回值
def div(x,y):
z=x/y
return z

div(4,2)
2.0
def div(x,y):
if y == 0:
return "除数不能为0"
else:
return x/y


div(4,2)
2.0
div(4,0)
'除数不能为0'
def div(x,y):
if y == 0:
return "除数不能为0"
else:
return x/y


div(4,2)
2.0
div(4,0)
'除数不能为0'

#位置参数
def myfunc(s,vt,o):
return "".join ((o,vt,s))

myfunc("我","打了","小甲鱼")
'小甲鱼打了我'
myfunc(o="我",vt="打了",s="小甲鱼")
'我打了小甲鱼'

##默认参数
def myfunc(s,vt,o="小甲鱼"):
return "".join ((o,vt,s))


myfunc("香蕉","吃")
'小甲鱼吃香蕉'
myfunc("香蕉","吃了","不二如是")
'不二如是吃了香蕉'

def myfunc(vt,s="苹果",o="小甲鱼"):
return "".join ((o,vt,s))

myfunc("拱了")
'小甲鱼拱了苹果'
help(abs)
Help on built-in function abs in module builtins:

abs(x, /)
Return the absolute value of the argument.

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.

abs(-1.6)
1.6
abs(-0.9)
0.9
sum([1,2,3,4],5)
15
def abc(a,/,b,c):
print(a,b,c)


abc(1,2,3)
1 2 3
def abc(a,*,b,c):
print(a,b,c)


abc
<function abc at 0x0000019AFF10B6D0>


def myfunc(*args):
print("有{}个参数".format(len(args)))
print("第二个参数是".format(args[1]))


myfunc("小甲鱼 ","不二如是")
有2个参数
第二个参数是
myfunc(1,2,3,4,5)
有5个参数
第二个参数是
def myfunc(*args):
print(args)


myfunc(1,2,3,4,5)
(1, 2, 3, 4, 5)
def myfunc():
return 1,2,3

myfunc()
(1, 2, 3)
x,y,z=myfunc()
x
1
y
2
z
3
def myfunc(*args):
print(type(args))


myfunc(1,2,3,4,5)
<class 'tuple'>
def myfunc(*args,a,b):
print(args,a,b)
myfunc(1,2,3,a=4,b=5)
(1, 2, 3) 4 5

def abc(a,*,b,c):
print(a,b,c)


abc(1,b=2,c=3)
1 2 3
def myfunc(**kwargs):
print(kwargs)


myfunc(a=1,b=2,c=3)
{'a': 1, 'b': 2, 'c': 3}
def myfunc(a,*b,**c):
print(a,b,c)


myfunc(1,2,3,4,x=5,y=6)
1 (2, 3, 4) {'x': 5, 'y': 6}
help(str.format)
Help on method_descriptor:

format(...)
S.format(*args, **kwargs) -> str

Return a formatted version of S, using substitutions from args and kwargs.
The substitutions are identified by braces ('{' and '}').

#解包参数

args=(1,2,3,4)
def myfunc(a,b,c,d):
print(a,b,c,d)
myfunc(*args)
1 2 3 4
kwargs={'a':1,'b':2,'c':3,'d':4}
myfunc(**kwargs)
1 2 3 4

#作用域
def myfunc():
x = 520
print(x)


myfunc()
520
x=880
def myfunc():
print(x)


myfunc()
880
def myfunc():
x = 520
print(x)


myfunc()
520
print(x)
880
x=880
id(x)
1765213861168
def myfunc():
print(id(x))


myfunc()
1765213861168
def myfunc():
x=520
print(id(x))


myfunc()
1765213861232
1765213861232
1765213861232

#global语句
x=880
def myfunc():
global x
x=520
print(x)


myfunc()
520
print(x)
520

#嵌套函数表
funA()
In funA,x= 520
def funA():
x=520
def funB():
x=880
print("In funB,x=",x)
funB()
print("In funA,x=",x)


funA()
In funB,x= 880
In funA,x= 520

#nonlocal语句
def funA():
x=520
def funB():
nonlocal x
x=880
print("In funB,x=",x)
funB()
print("In funA,x=",x)


funA()
In funB,x= 880
In funA,x= 880

#LEGB规则

str="小甲鱼把str给毁了"
str
'小甲鱼把str给毁了'

#闭包
def power(exp):
def exp_of(base):
return base**exp
return exp_of

square=power(2)
cube=power(3)
square(5)
25
cube(2)
8
def outer():
x=0
y=0
def inner(x1,y1):
nonlocal x,y
x +=x1
y +=y1
print(f"现在,x={x},y={y}")
return inner

move=outer()
move(1,2)
现在,x=1,y=2
move(-2,2)
现在,x=-1,y=4

#装饰器
import time
def time_master(func):
print("开始运行程序...")
start=time.time()
func()
stop=time.time()
print("结束程序运行")
print(f"一共耗费了{(stop-start):2f}秒。")


def myfunc():
time.sleep(2)
print("hello fishc")


time_master(myfunc)
开始运行程序...
hello fishc
结束程序运行
一共耗费了2.035986秒。

#lambda表达式
def squareX(x):
return x*x

squareX(3)
9
squareY=lambda y:y*y
squareY(3)
9
squareX
<function squareX at 0x000001B9A793B910>
squareY
<function <lambda> at 0x000001B9A793B2E0>
y=[lambda x:x*x,2,3]
y[0](y[1])
4
y[0](y[2])
9
mapped=map(lambda x:ord(x)+10,"fishc")
list(mapped)
[112, 115, 125, 114, 109]
def boring(x):
return ord(x)+10

list(map(boring,"fishc"))
[112, 115, 125, 114, 109]
list(filter(lambda x:x%2,range(10)))
[1, 3, 5, 7, 9]

#生成器
def counter():
i=0
while i<=5:
yield i
i +=1


counter()
<generator object counter at 0x000001B9A58A2180>
for i in counter():
print(i)


0
1
2
3
4
5

c=counter()
c
<generator object counter at 0x000001B9A7923220>
next(c)
0
next(c)
1
next(c)
2

next(c)
3
next(c)
4
next(c)
5

def fib():
back1,back2=0,1
while True:
yield back1
back1,back2=back2,back1+back2


f=fib()
next(f)
0
next(f)
1
next(f)
1
next(f)
2
next(f)
3
next(f)
5
next(f)
8
next(f)
13
next(f)
21
for i in f :
print(i)


34
55
89
144
233
377
610
987
1597
2584
................................
for i in t:
print(i)


t=(i**2 for i in range(10))
next(t)
0
next(t)
1
next(t)
4
next(t)
9
for i in t:
print(i)


16
25
36
49
64
81

#递归
def funC(i):
if i>0:
print("HHHSDJEH")
i -=1
funC(i)


funC(10)
HHHSDJEH
HHHSDJEH
HHHSDJEH
HHHSDJEH
HHHSDJEH
HHHSDJEH
HHHSDJEH
HHHSDJEH
HHHSDJEH
HHHSDJEH

def factIter(n):
result=n
for i in range(1,n):
result *=i
return result

factIter(5)
120
factIter(10)
3628800
def factRecur(n):
if n==1:
return 1
else:
return n*factRecur(n-1)


factRecur(5)
120
factRecur(10)
3628800
def fib(n):
a=1
b=1
c=1
while n>2:
c=a+b
a=b
b=c
n-=1
return c

fib(12)
144
def fibRecure(n):
if n ==1 or n ==2:
return 1
else:
return fibRecure(n-1)+fibRecure(n-2)


fibRecure(12)
144
fib(120)
5358359254990966640871840

##函数文档,类型注释,内省
def exchange(dollar,rate=6.32):
"""
功能:汇率转换,美元->人民币
参数:
-dollar 美元数量
-rate 汇率,默认值是6.32(2022-08-01)
返回值:
-人民币的数量
"""
return dollar*rate

exchange(20)
126.4
exchange(60)
379.20000000000005
help(exchange)
Help on function exchange in module __main__:

exchange(dollar, rate=6.32)
功能:汇率转换,美元->人民币
参数:
-dollar 美元数量
-rate 汇率,默认值是6.32(2022-08-01)
返回值:
-人民币的数量

def times(s:str,n:int)->str:
return s*n

times("ygashj",5)
'ygashjygashjygashjygashjygashj'
times(5,5)
25

#高阶函数

def add(x,y):
return x+y

import functools
functools.reduce(add,[1,2,3,4,5])
15
add(add(add(add(1,2),3),4),5)
15
functools.reduce(lambda x,y:x*y,range(1,11))
3628800

#偏函数

square=functools.partial(pow,exp=2)
square(2)
4
square(3)
9
cube=functools.partial(pow,exp=3)
cube(2)
8
cube(3)
27

#@wraps

 

标签:myfunc,return,函数,args,funA,print,def
From: https://www.cnblogs.com/chongqing/p/16587312.html

相关文章

  • django中视图函数的FBV和CBV
    1.什么是FBV和CBVFBV是指视图函数以普通函数的形式;CBV是指视图函数以类的方式。2.普通FBV形式defindex(request):returnHttpResponse('index')3.CBV形式3.1CBV形......
  • Python 内置函数getattr()
    优点可消除if...else Python面向对象中的反射通过字符串的形式操作对象的属性,trueorfalsePython中一切皆为对象,所以只要是对象都可以使用反射比如:实例对象、......
  • FB(S1C1): PInvokeStackImbalance对PInvoke函数的调用导致堆栈不对称
    FB(S1C1):PInvokeStackImbalance对PInvoke函数的调用导致堆栈不对称 问题:    C#语言对C语言导出函数进行调用时报出的错误. 方案:   设置调用约定Call......
  • CGO,基本数据类型转换2 和 函数调用
    CGO涉及的数据类型转换包含一下内容:数值类型字符串和切片类型结构体、联合体、枚举类型‘数组类型指针类型数组和指针间的转换切片和切片之间的转换前面3个咱......
  • 函数
    函数概述函数就是多行代码的抽取(多行代码会构成特定的功能)也叫方法;优点:减少冗余代码(重复代码放在函数里面,需要时调用)函数封装(特定的一些代码使用函数包起来)提高代码......
  • 常函数
    classPerson{public://this指针的本质是指针常量指针的指向是不可以修改的//constPerson*constthis;//在成员函数后面加const修饰的是this指......
  • 函数式接口:Function
    Function接口Function接口在java中主要用来转换类型通过调用apply方法将T类型转换为R类型抽象方法:applyRapply(Tvar1);代码样例publicclassMain{publics......
  • 函数的形参和实参不匹配会出现什么情况
    知识储备:js的函数参数和C语言等编程语言不同,没有参数重载,实参和形参之间的值传递或者地址传递;有的是js的相同函数名会被后面的参数覆盖,实参和形参的传递都是值传递;实参的......
  • python 中字符串 内置函数 find
     001、>>>str1="xabdxyabxykk"##测试字符串>>>str1'xabdxyabxykk'>>>str1.find("ab")##返回测试字符串中首次匹配ab的首字符的索......
  • 拷贝构造函数
    c++中的拷贝构造函数调用时机通常有三种情况1.使用一个已经创建完毕的对象来初始化一个新的对象2.值传递的方式给函数参数传值3.以值方式返回局部对象//情况1classP......