notes for p2s chapter 3

HydroOJ个人主页

教程

slides/chapter 3

任务

变量与函数

学习时间

5/16

笔记

变量Variables

A variable is a named value that references or stores a piece of data
C语言里需要类型转换的赋值,在Python里可以直接赋值

in python, instead of a box, variable is a tag pointing to the memory space that stores the content
//why can’t I consider variable as a box?
//if it is a tag(address), a should equals to b at last?

a=10
b=a
a=1
print(a,b)# ?

变量命名规则:

  • 必须以字母或下划线(_)开头
  • 命名可由字母、数字和下划线组成
  • 大小写敏感
  • 尽量避免使用保留字命名
  • //similar to C

保留字(keywords):

['False',
 'None',
 'True',
 '__peg_parser__',
 'and',
 'as',
 'assert',
 'async',
 'await',
 'break',
 'class',
 'continue',
 'def',
 'del',
 'elif',
 'else',
 'except',
 'finally',
 'for',
 'from',
 'global',
 'if',
 'import',
 'in',
 'is',
 'lambda',
 'nonlocal',
 'not',
 'or',
 'pass',
 'raise',
 'return',
 'try',
 'while',
 'with',
 'yield']
多变量赋值
a = b = c = 2
a, b, c = 1, 2, 6 # 元组的解包

函数FUNCTIONS

A function is a procedure (a sequence of statements) stored under a name that can be used repeatedly by calling the name.

  • 函数由两个部分组成:headerbody
    • header 用于定义函数接口(函数 名称参数
    • body 包含函数所需要执行的操作
def funcName(parameters): # mind ":"!
	body
	return # not necessary

//缩进两个或四个空格,但是要一致

语句与表达式Statements and Expressions

An expression is a data value or an operation that evaluates to a value.
Statements, by contrast, do not evaluate to a value, and we can’t print them. Usually they perform some action, though.

print()可以打印值或表达式,不能打印语句
//C语言中,printf(“%d”, x=5+4);会打印9

内置函数 Builtin Functions

abs()
max(2,3)
min(2,3)
pow(2,10)
round(2.354,2) # 取最近的一个整数(并不完全是四舍五入,二进制精度丢失)

//刚刚学了浮点数的表示,确实如此

变量作用域 Variable Scope

函数内的局部变量在函数外没有定义
see an example in visualizing code running step by step
我们应该尽量避免使用全局变量,但是在非常少的一些场合你会需要用到它

g = 100
def f(x):
    # 如果我们想要修改 g 的值,我们必须声明它是全局变量
    # 否则 Python 会假设它是局部变量
    # global g
    g = 1
    return x + g
print(f(5)) # 6
print(f(6)) # 7
print(g)    # 100

返回语句RETURN STATEMENTS

没有返回语句时,函数返回None

Helper Function

可以编写Helper Function,来存储那些经常被用到的一系列操作

函数不在大,小而美亦可
聚沙成塔

课后思考

递归&分治

想起搞C语言课程设计时,一个函数塞一堆代码,太臃肿了
要改掉这个坏习惯

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值