Python领进门(二)
常用快捷键
ctrl + 1(macOS: command + 1):注释/去注释
tab: 退格(可以同时选中多行一起退行)
shift+tab: 去退行
ctrl/command + delete/backspace: 删除直至下一个特殊字符
F5:运行
常用语句示例
条件判断
条件判断的句式是if…elif…else…,其中elif和else语句都不是必须的。
例子:
judge1 = True #True是布尔变量,对应数值为1,任何不为0的数也可判断为真
judge2 = False
if judge1: #注意冒号与退行的配合使用
print('judge1 is True')
elif not judge2: #表示取反
print('judge2 is True')
else:
print('judge2 is False')
常见布尔运算
包括数学常用的等号,不等号:
print(1 == 1, 2 > 1, 2 >= 1, 2 < 3, 1 != -1)
注意不一定是比较数值,其它类型的变量也是可以的:
a = [1,2]
b = [1,2]
print(a == b, a is b)
a = '12'
b = '12'
print(a == b, a is b)
#注意体会is和==的区别
除此之外还有与或非运算:
#与
print( True and True , True and False , False and True)
#或
print( True or True , True or False , False or True)
#非
print( not True , not False )
对于数组,如果我们希望得到每一个元素的布尔运算结果,需要按位操作:
from numpy import *
t = ones(3).astype(bool)
f = zeros(3).astype(bool)
print(t & f, t | f , ~t, t == f)
哪些变量在判断时会被认为是非真呢?
布尔变量False
数值0
空对象None
空字符串‘’
空list,空字典[],{}
……
条件循环
顾名思义,即满足某种条件的时候进行循环,句式while:
a = list(range(1,10,2))
print(a)
while(a.pop(0)<7):
print('元素小于7')
如果想要在循环中提前结束循环,可以使用continue和break语句,运行下面代码体会区别:
a = list(range(20))
i = 0
while(a[i] < 20):
print(a[i])
if a[i] < 5:
i+=1
print('执行continue')
continue
elif a[i] > 10:
i+=1
print('执行break')
break
else:
i+=1
for循环
句式为for … in …:
for i in range(9,0,-1):
print(i)
else
其实,for循环和while循环都是可以跟else语句的,以for循环为例我们可以体会一下:
for i in range(10):
if i > 5:#可以将5换成10试一试
print('执行了break')
break
else:
pass #pass表示无操作
else:
print('执行了for对应的else')
try…except…finally和with…as
这两个语句对于入门者而言用得比较少,推荐看廖雪峰博客:
https://www.liaoxuefeng.com/wiki/1016959663602400/1017598873256736
https://www.liaoxuefeng.com/wiki/1016959663602400/1017607179232640
作业
把上面的代码都自己试一遍,下次课可以学习文件的读写了!