MIT6.00 1x Lecture 2 - Core elements of programs 学习笔记

Lecture 2 - Core elements of programs 编程基础

2.1 Type of programming languages 编程语言的类别

• Goal: 目标(将我们想要的转化为计算机理解的)

– Need a way to describe algorithmic stepssuch that computer can use them to execute process  我们需要用一种方法来描述算法的步骤,使得计算机可以使用它们来执行过程(这种方法就是编程)

– Programming language defines syntax andsemantics needed to translate our computational ideas into mechanical steps  编程语言定义了需要将我们的计算思想转化为机械步骤的语法和语义

Options for programming languages 编程语言的选项(执行方式)

注:这里有好几种执行方式。分别介绍。

柱:首先是低级编程语言


• Lowlevel language uses instructions similar to internal control unit: 低级编程语言与我们上次看到的内部控制单元(的指令)非常相似

– Move data from one location toanother 从内存中某处移动数据到另一处

– Execute a simple ALU operation  执行一个简单的ALU(算数逻辑单元)操作(比如加/减/比较)

– Jump to new point in sequencebased on test 根据比较结果跳转到指令序列的一个新位置

•Checker confirms syntax, static semantics correct 检查器会确认语法,静态语义正确

•Interpreter just follows sequence of simple instructions 解释器仅能按序执行这些指令

注:之后是编译型语言


• A highlevel language uses more abstract terms – invert a matrix, compute a function 高级编程语言使用更抽象的术语——求逆矩阵,计算几个函数

• In acompiled language, those abstractions are converted back into low level instructions,then executed 在编译型语言中,那些抽象的东西首先将被检查,像之前那样,然后转化为低级代码

注:之后是解释型语言


• In aninterpreted language, special program converts source code to internal datastructure, then interpreter sequentially converts each step into low levelmachine instruction and executes  在解释型语言中,有一个特殊的程序能将源代码转化成一种内部中间数据结构,然后按序将每一步低级机器指令来执行(那表示我们每次只对一条指令进行转换和执行

• We aregoing to use Python, which belongs to this class of programming languages 我们将要使用的PYTHON 正是这种解释型编程语言

结论:在编译型语言中,代码通常更快,因为我们之前已经完成了所有的工作,即通过编译器将指令转换成低级机器指令,所以我们能让它们变得非常高效。也就是跑起来更快。但是问题之一是如果我们代码中存在漏洞或者错误,当已编译代码遇到了这个错误,那么要找出引起这个错误的原因通常非常困难,因为我们要进入到那些杂乱无章的编译后指令中去,寻找在我们实际指令中什么地方导致了那个错误,这将会是无比困难的。

    在解释型语言中,它可能会慢那么一点点,不是非常严重,因为我们实时进行着转换,一次一条指令。另一方面,一旦我们遇到错误或者漏洞时,通常能更容易的找到引起错误的地方,因为我们准确的知道,错误发生时,我们位于代码的什么地方

2.2 Python object     Python对象

Python programs   Python程序

• Program (or script) is a sequence of definitions andcommands 程序(或脚本)会包含一系列定义命令

– Definitions evaluated and commands executed by Python interpreterin a shell 定义是那些被计算和储存的东西,而命令则是“shell”程序中的Python解释器实际执行的东西

– Can be typed directly into a shell, or stored in a file that isread into the shell and evaluated (shell只是一个程序)它允许用户在其中输入命令,这些命令会被计算机的操作系统直接执行

注:它被叫做shell是因为它隐藏了操作系统的细节,只让我们直接(与程序)互动。

Command (or statement) instructs interpreter to dosomething 命令(或者说是语句)是指示解释器去做某事的东西

的东西

Objects 数据对象

• At heart, programs will manipulate dataobjects 本质上每个程序都会操作一个数据对象

• Each object has a type that defines the kinds of things programs can do to it 每个数据对象都有一个类型,它定义了程序可以对这个对象做的事情

• Objects are:  数据对象是

Scalar (i.e. cannot besubdivided), or 标量(不可被分割)

Non-scalar (i.e. haveinternal structure that can be accessed) 非标量(拥有一个可以访问的内部结构)

Scalar objects 标量对象(3种)

• int – used to represent integers, e.g., 5or 10082  整数——用来表示我们熟知的全部数字

• float – used to represent real numbers,e.g., 3.14 or 27.0 浮点数——用来表示实数,即那些有个小数点的数

• bool – used to represent Boolean valuesTrue and False 布尔——它表示真和假中的真值

• The built in Python function type returnsthe type of an object Python中”type()“函数会显示对象的类型(类似下面)


Expressions 表达式

• Objects and operators can be combined toform expressions, each of whichdenotes an object of some type 操作符和数据对象构成表达式

 •The syntax for most simple expressions is: 大部分简单的表达式语法是

-<object><operator><object>  <对象><操作符><另一个对象>

Operators on ints and floats 整数和实数中的操作符

• i + j – sum – if both are ints, result isint, if either is float, result is float  如果两个数据对象都是整数,我们可以把它们加起来也是整数。如果其中一个是浮点数,那加起来就是浮点数

• i - j – difference  减法

• i * j – product 乘法

• i / j – division – if both are ints,result is int, representing quotient without remainder  如果都是整数,结果也是整数,是没有余数的商

注:python3.5中,i/y统一会的得出精确地数,i//y会得出整数

• i % j – remainder  求余数

• i ** j – i raised to the power of j 乘方

Some simple examples 一些例子

>>> 3 + 5

 8

>>> 3.14 * 20

 62.8

>>> (2 + 3)*4

 20

>>> 2 + 3*4

 14

注:这里存在一个执行顺序的问题

Performing simple operations  执行简单操作

• Parentheses define sub-computations –complete these to get values before evaluating larger expression 括号定义了子运算,必须先运算括号里的值

– (2+3)*4

– 5*4

– 20

• Operator precedence: 操作符的优先级

– In the absence of parentheses (within which expressions are firstreduced), operators are executed left to right, first using **, then * and /,and then + and – 在没有括号情况下,操作符从左到右执行,首先是**,然后*和/ 然后加和减。

Comparison operators on ints and floats 整数和浮点数中的比较运算符

• i > j – returns True if strictlygreater than  如果大于返回:True

• i >= j – returns True if greater thanor equal  如果大于等于返回:True

• i < j

• i <= j

• i == j – returns True if equal  如果等于返回:True

• i != j – returns True if not equal 如果不等于返回:True

Operators on bools 布尔值的运算符

• a and b is True if both are True  a和b如果都为真才为真

• a or b is True if at least one is True  a和b至少一个为真

• not a is True if a is False; it is Falseif a is True  如果a是假的,非a就是真的,如果a是真的,非a就是假的

Type conversions (type casting) 类型转换

• We can often convert an object of onetype to another, by using the name of the type as a function  我们可以经常转换数据的类型,通过使用类型名字的函数

float(3) has the value of 3.0

int(3.9) truncates to 3

 

注:None在python中频繁的表示无意义

None有自己的数据类型 NoneType

None是一个特殊的常量。

None和False不同。

None不是0

None不是空字符串。

None和任何其他的数据类型比较永远返回False

你可以将None复制给任何变量,但是你不能创建其他NoneType对象。

 

注:--4等于0减负4?

 

提示 布尔值“True”和“true”不同,

布尔运算的操作顺序,

“括号”

“not”,

”and“,

”or

我们应该多用括号来让表达更清晰

 

round(x)函数将一个浮点数x四舍五入为最近的1的倍数,如round(0.4)=0,round(0.6)=1.0;如果x距离两个倍数值相等,如round(0.5)距离0和1.0相等,那么:

  python2把x四舍五入为远离0的最近倍数,如round(0.5)=1, round(-0.5)=-1;

  python3则会把x四舍五入为最近的偶数倍数,如round(0.5)=0,round(1.5)=2.0, round(2.5)=2.0

在python3中,round()会输出int类型

             round(i,0)输出的才是float类型

2.3 Variables and naming 变量和命名

Simple means of abstraction  抽象化的简单含义

• While we can write arbitrary expressions,it is useful to give names to values of expressions, and to be able to reusethose names in place of values 虽然我们可以写任意的表达式,但把他们写下来之后,通过一个名字把表达式的值储存下来,然后再任何我们需要他的时候,使用这个名字来得到值

• pi = 3.14159

• radius = 11.2

• area = pi * (radius**2)

Binding variables and values 绑定变量和值

• The statement pi = 3.14159 assigns thename pi to the value of the expression to the right of the =  pi=3.14159这个语句表示把pi这个名字绑定为等号右边的表达式的值

• Think of each assignment statement ascrea1ng a binding between a name and a value stored somewhere in the computer  我们在一个名字和一个值之间建立了关联关系,这个关系储存在计算机中某处

• We can retrieve the value associated witha name or variable by simply invoking that name, e.g., pi 我们可以很简单的通过引用这个名字得到与之相关的值


Changing bindings 改变关联关系

• Variable names can be rebound, byinvoking new assignments statements.  在已绑定了的变量名上,还可以另写一个赋值语言

• For example, if we now execute:  举个例子 巴拉巴拉

– radius = 11.2

• we get the diagram shown here. 这里有个图可以表示

• Note that this doesn’t change the valueassociated with area 注意,其他值并没改变(即使之前与改变的值相关)


2.4 Strings 字符串

Non-scalar objects 非标量对象

• We will see many different kinds ofcompound objects 我们会看到许多不同种类的复合物

• The simplest of these are strings,objects of type str 最简单的是字符串,str(代表string)类型

• Literals of type string can be writtenusing single or double quotes 这种类型的文字可以将他们放在一对单引号或者一对双引号中表示

‘abc’

“abc”

‘123’ – this is a string ofcharacters, not the number 这个一个字符串,不是数字

Operators on strings 字符串上的操作符

Len()函数代表字符串的长度

Extracting parts of strings 提取字符串的部分

• Indexing:  索引

‘abc’[0] returns the string ‘a’ 从零开始算起 0 1 2

‘abc’[2] returns the string ‘c’

‘abc’[3] is an error (as wecannot go beyond the boundaries of the string)

‘abc’[-1] returns the string ‘c’ (essentially counting backwards from the startof the string)  一个数是0 之后是 -2 -1

结论:第一个数必是0 之后按从小到大的顺序,如果是正数第二个数是1.如果是负数。最后一个数是-1

• Slicing: 切片技术

– If s is a string, the expression s[start:end] denotes thesubstring that starts at start, and ends at end-1    表达式[ 开始的数字:结束的数字  ],这个函数会截取从开始的数字到结束的数字减一这段的字符串(不会输出结束的数字表示的字符)

‘abc’[1:3] has the value ‘bc’ 

注: 如果省略开始的数字,Python会默认从0开始,如果省略结束的的数字,Python截取后面所有的字符。如果既省略开始又圣罗结束的话,他会输出完整的字符串

注:提取字符串命令还可以引入第三个参数k,即s[i:j:k] k表示步长,例如:

>>> s = 'Python is Fun!'

>>> s[1:12:2]

'yhni u' #本来截取的部位为ython is Fun2个步长表示跳过一个数

注:如果k是-1的,就代表字符串倒写


注意是冒号!!不是逗号

2.5 simple scripts 简单脚本

Programs (or scripts) 程序或脚本

• While we can type expressions directly toa Python interpreter (for example using an interface such as an IDLE shell), ingeneral we will want to include statements in a program file  我们现在可以在Python解释器中直接输入表达式了(IDLE shell),在一般情况下,我们想引入一个程序文件中的语句,这个单独的程序文件被我们存放在别的地方。

• Executing an expression from a scriptwill not produce any output; for that we need statements (not expressions),such as 执行储存为文件脚本的表达式时,不会产生任何输出(在shell中会,但是在脚本中,他不会),我们需要给他一个明确的语句而非表达式


Providing input 提供输入

• If we are going to write programs orscripts, we will need a way to incorporate input from a user. 如果我们要编写程序或脚本,我们将需要一个方法来获取来自用户的输入。

• We use the Python function raw_input, asin: 我们使用Python函数raw_input,如


注:在Python3.0中不需raw_input,只需input()

Some simple code 一些简单的代码

One can use variable names anywhere youmight use the expression whose value it holds 一旦我们做到这一点,我们就可以在任何表达式中,使用这些变量名了。


A straight line program 直线程序

Suppose we type the following into a file,and load it into a Python IDLE window 假设我们把一下的指令真正输入到了一个Python文件中


Some observations 一些现象

• Comments appear after a #  #号后面会出现注释

– These are very valuable, as they help a user understand decisionsthe programmer has made in creating the program  它们会帮助一个用户理解程序员做了什么

– Well commented code should be very readable by a user  真正好的代码都应该有明确的注释

• A straight line program simply executeseach statement in order, with no variation in order 这是一个直接程序,在顺序上没有改变,它从头到尾按顺序执行

• Most programs require more sophisticatedflow control 更多的程序代码中需要的是精确地控制流

2.6 branching programs 分支程序

Branching programs 分支程序

• The simplest branching statement is a conditional  在Python中最简单的分支语句是条件语句

– A test (expression that evaluates to True or False)  一个测试(计算结果为真或假的表达式)

– A block of code to execute if the test is True  如果是真,会执行一个代码块

– An optional block of code to execute if the test is False 如果是假,会执行另一个代码块


A simple example 一个例子

Some observations 一些观察

• The expression x%2 == 0 evaluates to Truewhen the remainder of x divided by 2 is 0  这个表达式只有在x除以2没有余数时才等于0,表示真

• Note that == is used for comparison,since = is reserved for assignment  双等号用来表示比较,一个等号用来表示为一个名字赋值

• The indentation is important – eachindented set of expressions denotes a block of instructions  缩进很重要,它表示一个指令块

– For example, if the last statement were indented, it would beexecuted as part of the else block of code 例如,如果最后一条语句进行缩进,它将作为代码块执行的其他部分

• Note how this indentation provides avisual structure that reflects the semantic structure of the program 注意这个缩进提供了一个可视化的结构,反映了程序的语义结构

We can have nested conditionals 我们可以做有嵌套的条件

And we can use compound Booleans 使用复合的布尔表达式

What have we added? 我们学到了什么

• Branching programs allow us to makechoices and do different things  分支程序使我们做出决定来做不同的事情

• But still the case that at most, eachstatement gets executed once.  尽管如此,每条语句最多只执行了一次

• So maximum time to run the programdepends only on the length of the program  程序所需运行的最长时间取决于程序的长度

• These programs run in constant time 这些程序都是以常数时间运行的

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值