- help():当记住如何使用help()的时候,就掌握了理解大多数其他函数的关键
- docstrings:文档字符串是一个三引号字符串(triple_quoted string)(可能跨越多行),紧跟在函数的头部之后。当我们在函数上调用 help() 时,它会显示文档字符串。
- 换行符:“\n”
1.理解help()函数
help(round)
help(print)
2.定义函数
Python虽然自带内置函数(builtin function)
#定义一个查找三个数字中最小差值的函数
def least_difference(a,b,c)
diff1 = abs(a-b) #取绝对值
diff2 = abs(a-c)
diff3 = abs(b-c)
return min(diff1,diff2,diff3)
#调用函数
print(
least_difference(1,10,100),
least_difference(1,10,10),
least_difference(5,6,7),
return很重要,要是不加上的话,最后会显示没有返回值。
3.默认参数(default arguments)
当我们调用 help(print) 时,我们看到 print 函数有几个可选参数。例如,我们可以为 sep 指定一个值,以便在打印的参数之间放置一些特殊字符串:
小例子
def greet(who = "Colin"):
print("Hello,",who)
#调用
greet()
greet(who = "Kaggle")
greet("world")
4.应用于函数的函数(functions applied functions)
def mult_by_five(x):
return 5 * x #x的五倍
def call(fn,arg):
return fn(arg)
def squared_call(fn,arg):
return fn(fn(arg))
print(
call(mult_by_five,1), #mult_by_five(1)
squared_call(mult_by_five,1), #mult_by_five(mult_by_five(1)) 相当于幂函数了
sep = "\n", #\n:是换行符
)
def mod_5(x):
return x % 5
print(
'Which number is biggest?'
max(100,51,14),
"Which number is the biggest modulo 5?',
max(100,51,14,key = mod_5),
sep = "\n",
)
练习
1.返回给定数字四舍五入到小数点后两位的值。(return the given number rounded to two decimal places)
def round_to_two_places(num):
return round(num,2)
# or return(round(num,ndigits=2))
当ndigits为负数时
cool,所以负数的形式是用来处理大数的情形
3.切换注释的方法
快捷键:ctrl+/
4.糖果分配问题
中间的"""是关于函数的介绍说明,当用?或help来查找的时候,会显示出来