目录
4 Fruitful functions and viod functions
1 Function calls
▲函数调用:函数名(参数1,参数2...),如
>>> type(32)
<class 'int'>
type为函数名,32为参数,返回函数调用的结果<class 'int'>
2 Build-in functions
python提供了许多内置函数用于解决各种问题,在创建变量时要避免使用这些内置函数作为变量名
▲如max取最大值,min取最小值
>>> max('Hello world')
'w'
>>> min('Hello world')
' '
>>>
▲len计算字符长度
>>> len('Hello world')
11
>>>
▲类型转换函数 int、float、str
>>> int('32')
32
>>> int('Hello')
ValueError: invalid literal for int() with base 10: 'Hello'
#####int不能转化字符
>>> int(3.99999)
3
>>> int(-2.3)
-2
#####int在计算时直接取整数部分,而不是进行四舍五入
>>> float(32)
32.0
>>> float('3.14159')
3.14159
#####float可以把整数转化成浮点数
>>> str(32)
'32'
>>> str(3.14159)
'3.14159'
▲数学计算函数,调用时要先加载math module
>>> import math
>>> print(math)
<module 'math' (built-in)>
#####math的类型是内置模块
The module object contains the functions and variables defined in the module. To access one of the functions, you have to specify the name of the module and the name of the function, separated by a dot (also known as a period). This format is called dot notation.
模块包含函数及变量,调用模块函数时用 模块名.函数名
>>> ratio = signal_power / noise_power
>>> decibels = 10 * math.log10(ratio) #####计算对数,e为底用math.log()
>>> radians = 0.7
>>> height = math.sin(radians) #####计算三角函数,math.cos,math.tan etc.
>>> math.sqrt(2) / 2.0 #####计算平方根
0.7071067811865476
▲取随机数,调用random module,生成的是伪随机数Pseudorandom numbers
random函数生成0-1之间的随机数,不包括1
import random
for i in range(10):
x = random.random() #random函数生成0-1之间的随机数,不包括1
print(x)
randint函数有两个参数low和high,生成low-high之间的随机数,不包括low和high值
>>> random.randint(5, 10)
5
>>> random.randint(5, 10)
9
choice函数在给定的列表中随机选择一项
>>> t = [1, 2, 3]
>>> random.choice(t)
2
>>> random.choice(t)
3
3 Adding new functions
▲用def定义函数,具体格式:
def print_lyrics():#def+函数名(参数1,参数2...)+:
print("I'm a lumberjack, and I'm okay.")
print('I sleep all night and I work all day.')#函数主体,需要缩进
▲定义完成后即可调用 print_lyrics,其类型为function
>>> print_lyrics()
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
>>> print(print_lyrics)
<function print_lyrics at 0xb7e99e9c>
>>> print(type(print_lyrics))
<class 'function'>
▲可以在新的函数里调用已有的函数
def repeat_lyrics():
print_lyrics()
print_lyrics()
▲对于有参数的函数,参数可以是value,variable或expression
def print_twice(bruce):
print(bruce)
print(bruce)
>>> print_twice('Spam') ##参数是字符
Spam
Spam
>>> print_twice(17) ##参数是数值
17
17
>>> import math
>>> print_twice(math.pi) ##参数是表达式
3.141592653589793
3.141592653589793
4 Fruitful functions and viod functions
Some of the functions we are using, such as the math functions, yield results; for lack of a better name, I call them fruitful functions. Other functions, like print_twice, perform an action but don’t return a value. They are called void functions.
fruitful functions 有返回值,可以将返回值赋给一个变量
void functions无返回值,只执行一些命令
>>> result = print_twice('Bing')
Bing
Bing
>>> print(result)
None
>>> print(type(None))
<class 'NoneType'> ####result中没有内容,类型为NoneType