【MIT 6.0001 课程笔记】Lecture 2. Branching and Iteration

Lecture 2. Branching and Iteration

随堂阅读资料

  • Chapter 2.2 2.3.1, 2.4, and 3.2
  • PPT Lecture 2

作业

  • Problem Set 1

正式笔记

Strings 字符串类

  • 字符串类里可以包含如字母、特殊符号、空格、数字等元素
  • 利用双引号括住内容,即为字符串
  • 字符串可通过加法和乘法进行字符串拼接
hi = "hello there"
name = "ana"
greet = hi + name
greeting = hi + " " + name
silly = hi + " " + name * 3

input/output

print语法

  • 用于输出数据到终端
x = 1
print(x)
x_str = str(x)
#可用逗号拼接,逗号在输出中转换为空格
print("my fav num is", x, ".", "x =", x)
#可用加号拼接,不带空格
print("my fav num is", + x_str +"." +"x =" + x_str)

input语法

  • 先print出input里的引号内容
  • 用户输入数据
  • 将用户输入的数据存储为一个字符串变量
  • 如果要调用用户输入作为非字符串变量(如int),需要在input外套数据类型(如int() )
text = input ("Type anything ...")
print(5*text)

num = int(input("Type a number ..."))
print(5*num)

对比操作

  • 对比操作可用于int float string
  • 对比结果为布尔值bool
i > j
i >= j
i < j
i <= j
i == j
i != j#不等于

针对布尔值的逻辑操作符

  • not a 非
  • a and b 与
  • a or b 或

image-20201129121206671

对比示例

pset_time= 15
sleep_time= 8
print(sleep_time> pset_time)
derive = True # 赋值 赋布尔值
drink = False # 赋值 赋布尔值
both = drink and derive
print(both)

条件判断

如图,可用简单的条件判断规则找到迷宫终点。

image-20201129121349379

Control Flow - Branching 控制流之分支(if语句)

  • condition 的值为bool
  • 如果是true,执行if下面的expression
if<condition>:
    <expression>
    <expression>
    ...

if<condition>:
	<expression>
	<expression>
	...
else:
	<expression>
	<expression>
	...
    
if <condition>:
	<expression>
	<expression>
	...
elif<condition>:
	<expression>
	<expression>
	...
else:
	<expression>
	<expression>
	...

缩进的重要性

  • 缩进在python中非常重要
  • 缩进决定了判断的优先级,其他语言常用{}来区别优先级

x = float(input("Enter a number for x: "))
y = float(input("Enter a number for y: "))
if x == y:
    print("x and y are equal")
	if y != 0:
		print("therefore, x / y is", x/y)
elif x < y:
    print("x is smaller")
else:
    print("y is smaller")
print("thanks!")
    

“=” vs “==”

  • 等号意味着赋值,双等号意味着判断是否相等
  • 如果condition里只出现了等号,如if(x=y),语法报错
x = float(input("Enter a number for x: "))
y = float(input("Enter a number for y: "))
if x == y:
	print("x and y are equal")
	if y != 0:
		print("therefore, x / y is", x/y)
elif x < y:
	print("x is smaller")
else:
	print("y is smaller")
print("thanks!")

小例子:塞尔达传说——迷失丛林

主人公被困入丛林,可选择向左或向右,如果走错了,重新回到当前画面起点,如果走对了,离开。

image-20201129122212923

  • 如果用if语句,过于繁琐
if <exit right>:
    <set background to woods_background>
	if <exit right>:
		<set background to woods_background>
		if <exit right>:
			<set background to woods_background>
			and so on and on and on...
		else:
			<set background to exit_background>
    else:
		<set background to exit_background>
else:<set background to exit_background>
  • 可用while代替
while <exit right>:
    <set background to woods_background>
<set background to exit_background>

Control Flow - while loops 控制流之循环(while语句)

image-20201129123846320

while <condition>:
	<expression>
	<expression>
	...
  • condition里是布尔值
  • 如果condition为真,执行循环
  • 执行完毕后返回第一行再次判断
  • 直至condition为假,停止循环

Control Flow - while and for loops 控制流之有限循环(while&for语句)

  • 可以按次数迭代
# while loop
n = 0
while n < 5:
	print(n)
	n = n+1
# for loop
for n in range(5):
	print(n)
for <variable> in range(<some_num>):
	<expression>
	<expression>
	...
  • 每次执行后,variable的值发生变化
  • 第一次,variable为最小起始值
  • 下一次,variable+1

for语句——字符串的遍历

total = 0
#c的值变化:'1'->'2'->'3'->'4'...->'9'
for c in "123456789":
    total = total + int(c)
print total
#对123456789字符串中的数字求和并输出结果

range的用法

  • range可用于设置起点、终点、步长
  • 默认为起点=0,步长=1
  • 一直循环到stop-1(即i==stop时,不执行for的操作)
  • range里必须是int数
  • 如果step是负数,则start要大于stop
mysum= 0
	for iin range(7, 10):
		mysum+= i
	print(mysum)

mysum= 0
for iin range(5, 11, 2):
	mysum+= i
print(mysum)	
range的进阶问题
x = 4
for i in range(0,x):
    print i
    x = 5 

如果在循环内部修改x的值,是否会影响到循环次数?

  • 不会
  • range函数会在第一次循环之前求值,之后循环中不会再次求值
x = 4
for j in range(0,x):
    for i in range(x):
    	print i
   		x = 2
​```
期望结果
在执行循环前,根据x=4range(0,x),已经确定了一层(外层)需要循环4# j=0 一层循环第1轮,二层循环4次
0
1
2
3
# j=1 一层循环第2轮,二层循环的x已被改变,因此二层循环2次
0 
1
# j=2 一层循环第3轮,二层循环2次
0
1
# j=3 一层循环第4轮,二层循环2次
0
1
​```

break 语句

  • 立刻退出当前循环
  • 跳过当前循环后续语句
  • 只跳出当前的这一个循环(最小循环)
while <condition_1>:
	while <condition_2>:
		<expression_a>
		break
		<expression_b>#不会被执行
	<expression_c>
mysum= 0
for i in range(5, 11, 2):
    mysum+= i
    if mysum==5:
    	break
    	mysum+= 1
print(mysum)
#输出为5

for vs while

  • for
    • 可定循环次数
    • 可break
    • 有一个计数器counter
    • 可以用while loop来写for loop
  • while
    • 无限循环
    • 可break
    • 可用counter,但必须在loop外初始化,并且在loop内改变counter的值
    • 可能不能用for loop来表达 while loop
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值