CS61A Lecture2

1、常用函数

max(变量,变量,...,...,...)   //求一系列数最大值函数
min(变量,变量,...,...,...)   //求一系列数最小值函数
pow(变量a,变量b)    //求变量a的变量b次方



from operator import mul,add,sub
add(变量1,变量2,....)    //求所有变量的总和
mul(变量1,变量2,....)    //求所有变量的乘积
sub(变量a,变量b)    //求变量a,b的差值


from math import sqrt
sqrt(x)    //求x的平方根

可以参考 Python3 库文档

2、import 语句--导入库函数

非内嵌函数需要从Python库中导入使用

from XXX(函数库) import XXX(函数)

ex:
from operator import mul

3、赋值

>>> max
<built-in function max>
>>> f = max
>>> f
<built-in function max>
>>> f(2, 3, 4)
4
>>> f = 2
>>> f
2
>>> max = 5
>>> max
5
>>> x = 2
>>> x = x + 1
>>> x
3
>>> a, c = 2 , 3    //在单个语句中为多个变量分配值,左右都用逗号隔开
//此时 a = 2, b = 3


//对于多重赋值,所有 = 右边的表达式都会先求值,然后再与左边的名称绑定
>>> a = 2
>>> b = 5
>>> a, b = a + b, a //先计算a + b = 7 再绑定 a
>>> a
7
>>> b
2

//可以在单个语句内交换两个变量的值
>>> x, y = 3, 4.5
>>> y, x = x, y
>>> x
4.5
>>> y
3

4、定义函数

def 函数名(变量,变量,...):
    return 返回内容
ex:
from operator import add
def exam_scores(x,y):
    return add(x,y)/2    //返回x,y的平均值
exam_scores(70,90)    //调用函数

___________________________________________________________________________________________

>>> def g():
	return 1

>>> g()
1
>>> g
<function g at 0x0000017758CD9940>
>>> g=2
>>> g
2
>>> g()
Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    g()
TypeError: 'int' object is not callable

5、在环境中查找名称

from operator import mul
mul(3,4)
def square(square):
    return square*square

>>> square
<function square at 0x0000021B41C47C10>

方便代码 帧 理解的环境图显示器 Online Python Tutor - Composing Programs - Python 3

6、纯函数和非纯函数

        纯函数:在调用时除了返回值外不会造成其他任何影响,而且在使用相同的参数调用纯函数时总是会返回相同的值

        非纯函数:除了返回值外,调用一个非纯函数还会产生其他改变解释器和计算机的状态的副作用

>>> print(print(2),print(3))
2
3
None None

纯数函数
abs()//绝对值函数
pow()//指数函数

非存数函数
print()
他返回值为None,副作用输出()内的值/字符串


>>> def include(x):
	x    //没有出现return 没有返回值
>>> include(2)
>>> x=include(2)
>>> x+2
Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    x+2
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
//None和int类型是不能进行运算的


//print()不应该使用在赋值语句中
>>> two = print(2)    //其返回值None存储在two中
2
>>> print(two)    //输出None
None

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值