⑴ python 定义函数
python 定义函数:
在Python中,可以定义包含若干参数的函数,这里有几种可用的形式,也可以混合使用:
1. 默认参数
最常用的一种形式是为一个或多个参数指定默认值。
>>> def ask_ok(prompt,retries=4,complaint='Yes or no Please!'):
while True:
ok=input(prompt)
if ok in ('y','ye','yes'):
return True
if ok in ('n','no','nop','nope'):
return False
retries=retries-1
if retries<0:
raise IOError('refusenik user')
print(complaint)
这个函数可以通过几种方式调用:
只提供强制参数
>>> ask_ok('Do you really want to quit?')
Do you really want to quit?yes
True
提供一个可选参数
>>> ask_ok('OK to overwrite the file',2)
OK to overwrite the fileNo
Yes or no Please!
OK to overwrite the fileno
False
提供所有的参数
>>> ask_ok('OK to overwrite the file?',2,'Come on, only yes or no!')
OK to overwrite the file? test
Come on, only yes or no!
OK to overwrite the file?yes
True
2. 关键字参数
函数同样可以使用keyword=value形式通过关键字参数调用
>>> def parrot(voltage,state='a stiff',action='voom',type='Norwegian Blue'):
print("--This parrot wouldn't", action, end=' ')
print("if you put",voltage,"volts through it.")
print("--Lovely plumage, the",type)
print("--It's",state,"!")
>>> parrot(1000)
--This parrot wouldn't voom if you put 1000 volts through it.
--Lovely plumage, the Norwegian Blue
--It's a stiff !
>>> parrot(action="vooooom",voltage=1000000)
--This parrot wouldn't vooooom if you put 1000000 volts through it.
--Lovely plumage, the Norwegian Blue
--It's a stiff !
>>> parrot('a thousand',state='pushing up the daisies')
--This parrot wouldn't voom if you put a thousand volts through it.
--Lovely plumage, the Norwegian Blue
--It's pushing up the daisies !
但是以下的调用方式是错误的:
>>> parrot(voltage=5, 'dead')
SyntaxError: non-keyword arg after keyword arg
>>> parrot()
Traceback (most recent call last):
File "<pyshell#57>", line 1, in <mole>
parrot()
TypeError: parrot() missing 1 required positional argument: 'voltage'
>>> parrot(110, voltage=220)
Traceback (most recent call last):
File "<pyshell#58>", line 1, in <mole>
parrot(110, voltage=220)
TypeError: parrot() got multiple values for argument 'voltage'
>>> parrot(actor='John')
Traceback (most recent call last):
File "<pyshell#59>", line 1, in <mole>
parrot(actor='John')
TypeError: parrot() got an unexpected keyword argument 'actor'
>>> parrot(voltage=100,action='voom',action='voooooom')
SyntaxError: keyword argument repeated
Python的函数定义中有两种特殊的情况,即出现*,**的形式。
*用来传递任意个无名字参数,这些参数会以一个元组的形式访问
**用来传递任意个有名字的参数,这些参数用字典来访问
(*name必须出现在**name之前)
>>> def cheeseshop1(kind,*arguments,**keywords):
print("--Do you have any",kind,"?")
print("--I'm sorry, we're all out of",kind)
for arg in arguments:
print(arg)
print("-"*40)
keys=sorted(keywords.keys())
for kw in keys:
print(kw,":",keywords[kw])
>>> cheeseshop1("Limbuger","It's very runny, sir.","It's really very, very runny, sir.",shopkeeper="Michael Palin",client="John",sketch="Cheese Shop Sketch")
--Do you have any Limbuger ?
--I'm sorry, we're all out of Limbuger
It's very runny, sir.
It's really very, very runny, sir.
----------------------------------------
client : John
shopkeeper : Michael Palin
sketch : Cheese Shop Sketch
>>>
3. 可变参数列表
最常用的选择是指明一个函数可以使用任意数目的参数调用。这些参数被包装进一个元组,在可变数目的参数前,可以有零个或多个普通的参数
通常,这些可变的参数在形参列表的最后定义,因为他们会收集传递给函数的所有剩下的输入参数。任何出现在*args参数之后的形参只能是“关键字参数”
>>> def contact(*args,sep='/'):
return sep.join(args)
>>> contact("earth","mars","venus")
'earth/mars/venus'
4. 拆分参数列表
当参数是一个列表或元组,但函数需要分开的位置参数时,就需要拆分参数
调用函数时使用*操作符将参数从列表或元组中拆分出来
>>> list(range(3,6))
[3, 4, 5]
>>> args=[3,6]
>>> list(range(*args))
[3, 4, 5]
>>>
以此类推,字典可以使用**操作符拆分成关键字参数
>>> def parrot(voltage,state='a stiff',action='voom'):
print("--This parrot wouldn't", action,end=' ')
print("if you put",voltage,"volts through it.",end=' ')
print("E's", state,"!")
>>> d={"voltage":"four million","state":"bleedin' demised","action":"VOOM"}
>>> parrot(**d)
--This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !
5. Lambda
在Python中使用lambda来创建匿名函数,而用def创建的是有名称的。
python lambda会创建一个函数对象,但不会把这个函数对象赋给一个标识符,而def则会把函数对象赋值给一个变量
python lambda它只是一个表达式,而def则是一个语句
>>> def make_incrementor(n):
return lambda x:x+n
>>> f=make_incrementor(42)
>>> f(0)
42
>>> f(2)
44
>>> g=lambda x:x*2
>>> print(g(3))
6
>>> m=lambda x,y,z:(x-y)*z
>>> print(m(3,1,2))
4
6. 文档字符串
关于文档字符串内容和格式的约定:
第一行应该总是关于对象用途的摘要,以大写字母开头,并且以句号结束
如果文档字符串包含多行,第二行应该是空行
>>> def my_function():
"""Do nothing, but document it.
No, really, it doesn't do anything.
"""
pass
>>> print(my_function.__doc__)
Do nothing, but document it.
No, really, it doesn't do anything.
⑵ python中函数与变量之间的位置怎么确定
这样理解吧,如果运行之后你的字符串改变了,那就是放在后面写。
如果只是获取你的字符串的一些属性的话,那就放在前面。
⑶ python如何定义和调用函数
自定义函数用
def 函数名(参数):
(缩进)写具体的函数部分,和写普通程序一样,只不过用return来返回需要的结果。
主程序里面和使用普通内置函数一样,函数名(参数)。
⑷ 在python中定义函数
涉及到状态保存,可以使用函子(书上这么翻译的,不晓得其他人是不是也这样叫),给你个例子,你比对着改。如果不懂,自己再延这个方向去查看资料。
classStrip:
def__init__(self,characters):#初始化,将需要保留的状态信息存起来
self.characters=characters
def__call__(self,string):#创建的函子被使用时,自动调用__call__
returnstring.strip(self.characters)
#下面是使用方法,两个语句是密切衔接的。
strip_punctution=Strip(',;:.!?')#字符串参数将被__init__吃进去,并且保留在class中,
#相当于一种状态保存的方法,在你的例子中,你可以将用户表达式通过这种方式保存起来
strip_punctution('helloworld!')#return'helloworld',他的功能是剥离characters
#字符串中出现的字符,此处把感叹号去掉了,
#这就是函子典型的使用方法,class中的__call__函数被自动调用,在你的
#例子中,你可以通过这样的方式调用函数,就不用每次重新输入表达式了。
⑸ python里函数的定义
定义:
def 函数名(形参1,形参2='初始定义的内容'):
函数中执行的内容
调用:
函数名(实参1)或函数名(形参2=实参2,形参1=实参1)或函数名(实参1,实参2)
⑹ Python中定义函数的使用方法
4.6. 定义函数
我们可以创建一个用来生成指定边界的斐波那契数列的函数:
>>> def fib(n): # write Fibonacci series up to n
... """Print a Fibonacci series up to n."""
... a, b = 0, 1
... while a < n:
... print(a, end=' ')
... a, b = b, a+b
... print()
...
>>> # Now call the function we just defined:
... fib(2000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
关键字 def 引入了一个函数 定义。在其后必须跟有函数名和包括形式参数的圆括号。函数体语句从下一行开始,必须是缩进的。
函数体的第一行语句可以是可选的字符串文本,这个字符串是函数的文档字符串,或者称为 docstring。(更多关于 docstrings 的信息请参考 文档字符串) 有些工具通过 docstrings 自动生成在线的或可打印的文档,或者让用户通过代码交互浏览;在你的代码中包含 docstrings 是一个好的实践,让它成为习惯吧。
函数 调用 会为函数局部变量生成一个新的符号表。确切的说,所有函数中的变量赋值都是将值存储在局部符号表。变量引用首先在局部符号表中查找,然后是包含函数的局部符号表,然后是全局符号表,最后是内置名字表。因此,全局变量不能在函数中直接赋值(除非用 global 语句命名),尽管他们可以被引用。
函数引用的实际参数在函数调用时引入局部符号表,因此,实参总是 传值调用 (这里的 值 总是一个对象 引用 ,而不是该对象的值)。[1] 一个函数被另一个函数调用时,一个新的局部符号表在调用过程中被创建。
一个函数定义会在当前符号表内引入函数名。函数名指代的值(即函数体)有一个被 Python 解释器认定为 用户自定义函数 的类型。 这个值可以赋予其他的名字(即变量名),然后它也可以被当作函数使用。这可以作为通用的重命名机制:
>>> fib
>>> f = fib
>>> f(100)
0 1 1 2 3 5 8 13 21 34 55 89
如果你使用过其他语言,你可能会反对说:fib 不是一个函数,而是一个方法,因为它并不返回任何值。事实上,没有 return 语句的函数确实会返回一个值,虽然是一个相当令人厌烦的值(指 None )。这个值被称为 None (这是一个内建名称)。如果 None 值是唯一被书写的值,那么在写的时候通常会被解释器忽略(即不输出任何内容)。如果你确实想看到这个值的输出内容,请使用 print() 函数:
⑺ python如何在命令行定义函数
Python在命令行定义函数的方法如下:
打开电脑运行窗体,输入cmd,点击确定
命令行窗口,输入python,进入python命令行,编写函数后,敲两次回车,即定义好了函数
测试函数可以正常使用
更多Python相关技术文章,请访问Python教程栏目进行学习!以上就是小编分享的关于python如何在命令行定义函数的详细内容希望对大家有所帮助,更多有关python教程请关注环球青藤其它相关文章!
⑻ python怎么快速定位函数位置
使用pycharm然后直接使用F12就可以直接转到函数定位位置
也可以使用Structure查看函数,直接就可以定位到函数位置
⑼ Python如何定义一个函数
没注意 把x y改成 a b 应该满足题目了
def divideExactly(x, y):
list1 = []
for i in range(x, y):
if i % 7 == 0:
if i % 5 != 0:
list1.append(i)
l = ','.join(str(i) for i in list1)
print(l)
divideExactly(10, 100)