1.输出
print("%d dogs"%2)
2 dogs
print("I am \ a good boy")
I am a good boy
age=19
name=''phil
print('{0} is {1} years old'.format(name, age))
print('Why is {0} playing with that python?'.format(name))
phil is 19 years old
Why is phil playing with that python ?
'{0:.3}'.format(1/3)
'{0:_^11}'.format('hello') #fill with underscores(_)with the text
'{name} wrote {book}'.format(name='phil',book='untitled book') #keyword-based
'0.333'
'(三根下划线)hello(三根下划线)'
'phil wrote untitled book'
2.全局变量
global 语句被用来声明 x 是全局的
3.默认参数
只有在形参表末尾的那些参数可以有默认参数值,即你不能在声明函数形参的时候,先声明有默认值的形参而后声明没有默认值的形参。这是因为赋给形参的值是根据位置而赋值的。例如, def func(a, b=5) 是有效的,但是 def func (a=5, b) 是无效的。
4.关键参数
- 默认参数
def func(a, b=5, c=10):
print('a is', a, 'and b is', b, 'and c is', c)
func(3, 7)
func(25, c=24)
func(c=50, a=100)
a is 3 and b is 7 and c is 10
3 a is 25 and b is 5 and c is 24
4 a is 100 and b is 5 and c is 50
传入func()的参数,若不直接指定a,b,c,则从a开始传值,缺省就用默认值。
- VarArgs 参数
def total(initial=5, *numbers, **keywords):
count = initial
for number in numbers:
count += number
for key in keywords:
count += keywords[key]
return count
print(total(10, 1, 2, 3, vegetables=50, fruits=100))
166
当我们定义一个带星的参数,像 *param 时,从那一点后所有的参数被收集为一个叫做 ’param’ 的列表;当我们定义一个带两个星的参数,像 **param 时,从那一点开始的所有的关键字参数会被收集为一个叫做 ’param’ 的字典。
3)keyword_only参数
如果想指定特定的关键参数为 keywor-only 而不是位置参数,可以在带星的参数后申明
def total(initial=5, *numbers, vegetables):
count = initial
for number in numbers:
count += number
count += vegetables
return count
print(total(10, 1, 2, 3, vegetables=50))
print(total(10, 1, 2, 3,))
# Raises error because we have not supplied a default argument
value for 'vegetables'
66
Traceback (most recent call last):
File "test.py", line 12, in <module>
print(total(10, 1, 2, 3))TypeError: total() needs keyword-only argument vegetables
工作原理:
在带星号的参数后面申明参数会导致 keyword-only 参数。如果这些参数没有默认值,且像上面那样不给关键参数赋值,调用函数的时候会引发错误。
如果你想使用 keyword-only 参数,但又不需要带星的参数,可以简单地使用不使用名字的空星,如 def total(initial=5, *, vegetables)
注:
奇妙小知识
def printMax(x, y):
'''Prints the maximum of two numbers.
The two values must be integers.'''
x = int(x) # convert to integers, if possible
y = int(y)
if x > y:
print(x, 'is maximum')
else:
print(y, 'is maximum')
printMax(3, 5)
print(printMax.__doc__)
#输出:
#5 is maximum
#Prints the maximum of two numbers.
#The two values must be integers.
如何工作
在函数的第一个逻辑行的字符串是这个函数的文档字符串。注意, DocStrings 也适用于模块和类,我们会在后面相应的章节学习它们。
文档字符串的惯例是一个多行字符串,它的首行以大写字母开始,句号结尾。第二行是空行,从第三行开始是详细的描述。强烈建议你在你的函数中使用文档字符串时遵循这个惯例。你可以使用 doc(注意双下划线)调用 printMax 函数的文档字符串属性(属于函数的名称)。请记住 Python 把每一样东西都作为对象,包括这个函数。我们会在后面的类一章学习更多关于对象的知识。如果你已经在 Python 中使用过 help() ,那么你已经看到过 DocStings 的使用了!它所做的只是抓取函数的doc 属性,然后整洁地展示给你。你可以对上面这个函数尝试一下 —— 只是在你的程序中包括 help(printMax) 。记住按 q 退出 help 。自动化工具也可以以同样的方式从你的程序中提取文档。因此,我强烈建议你对你所写的任何正式函数编写文档字符串。随你的 Python 发行版附带的 pydoc 命令,与 help() 类似地使用 DocStrings 。
网友评论