重读LPTHW-Lesson37

时间:2021-08-18 00:25:50

这次是复习课  复习python符号  整理如下

1.逻辑运算符not、and、or

python中逻辑运算符包括not(布尔非)、and(布尔与)、or(布尔或)。注意以下几点:

①运算规则:重读LPTHW-Lesson37

例:重读LPTHW-Lesson37

②运算优先级:not的优先级大于and和or的优先级,而and和or的优先级相等。逻辑运算符的优先级低于关系运算符,必须先计算关系运算符,然后再计算逻辑运算符

 print not 1 and 0
print not (1 and 0)
print 1 <= 2 and False or True
print 1<=2 or 1 > 1 + 2

第一行  先计算not 1再计算and 0,输出:False

第二行  先计算括号内的and,再计算not,输出:True

第三行 先计算1 <= 2关系式,再计算and运算,最后计算or,输出:True

第四行  先计算1 <= 2关系式,再计算1 > 1+2 关系式,最后计算or,输出:True

2.with-as

with A() as B:

block

这个语句中,A()是一个类,A()类中必须有两个方法:__enter__()方法和__exit__()方法。

在执行with语句时,首先创建类A的一个临时对象,然后调用对象的__enter__()方法,并将这个方法的返回值赋值给B。接下来,执行block语句块(若__enter__()方法出现异常,会直接跳过,继续执行block代码块)。在block代码块执行完毕后,调用对象的__exit__()方法。

实例:

class people(object):
def __enter__(self):
print "Enter people"
return "Chinese"
def __exit__(self,type,value,traceback):
print "Exit people"
with people() as cn:
print cn

输出:

Enter people
Chinese
Exit people

注解:①创建临时对象people(),执行__enter__(),本例中是打印出"Enter people",然后将__enter__()的返回值即''Chinese"返回给变量'cn'

②执行语句块,本例中是打印出变量cn的值,输出"Chinese"

③调用__exit__()。本例中,调用__exit__()方法打印"Exit people"。

④本例中,__exit__()的三个参数type,value,traceback在异常处理中有很大作用,这也是with语句的强大之处,即它可以处理异常。

3.assert      assert语句用来声明/确保某个条件是True,并且在not True时引发一个错误。如你确信某个正在列表里至少有一个元素,要验证这一点,并且在列表中没有元素的时候即为not True的时候引发一个错误(会触发'AssertionError'错误),这种情况下应该运用assert语句。

重读LPTHW-Lesson37

4.break

break语句用来中止循环,即使循环条件仍然为真或序列没有完全递归,也停止执行循环语句,且对应的else语句将不执行。

# -*- coding:utf-8 -*-
while True:
s = raw_input("Enter Something:") #获取用户输入
if s == 'quit':
break #用户输入'quit'时,中止循环结束游戏
print "Your input is %s,its length is %d." % (s,len(s))
print "Game Over"

输出:

 Enter Something:Python is number one
Your input is Python is number one,its length is 20.
Enter Something:I love programming
Your input is I love programming,its length is 18.
Enter Something:I will be a good programmer
Your input is I will be a good programmer,its length is 27.
Enter Something:quit
Game Over

5.class

定义类:

class person(object):
pass

6.continue

continue语句用来跳过当前循环块中的剩余部分,继续进行下一轮循环

while True:
s = raw_input("Enter Something:")
if len(s) < 3:
continue #当输入长度小于3时,不执行任何处理
print "Congratulations! Your enter is effcetive.Its length is %d." % len(s)

输出:

Enter Something:a
Enter Something:12
Enter Something:123
Congratulations! Your enter is effcetive.Its length is 3.

7.def

定义函数:

def func(x):
pass

8.del

del用来删除列表、字典中的元素以及变量

 >>> list1 = ['a','b','c','d']
>>> dict1 = {'a': 'A','b': 'B','c': 'C','d': 'D'}
>>> del list1[1]
>>> list1
['a', 'c', 'd']
>>> del list1[0:2]
>>> list1
['d']
>>> del dict1['a']
>>> dict1
{'c': 'C', 'b': 'B', 'd': 'D'}
>>> del dict1['b']
>>> dict1
{'c': 'C', 'd': 'D'}
>>> del list1
>>> list1 Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
list1
NameError: name 'list1' is not defined
>>> del dict1
>>> dict1 Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
dict1
NameError: name 'dict1' is not defined
>>> x = 2
>>> x
2
>>> del x
>>> x Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
x
NameError: name 'x' is not defined

9.elif、else

elif即else if,和else都是if语句块的一部分:

if 0:
pass
elif 1:
pass
else:
pass

10.except

try...except语句用来处理异常,其执行程序如下:

①try...except语句把通常的语句放在try块中,从try语句块开始执行,若无异常,则执行else语句(存在else的前提下)。

②若在执行try句块中出现异常,则中断try块的执行并跳转到相应的异常处理块except块中执行。其先从第一个exceptXX处开始匹配,找到对应的异常类型就进入对应exceptXX句块处理;如果没有找到则直接进入except块处理。

③except句块是可选项,如果没有提供,调用默认的python处理器,处理方式则是终止应用程序并打印提示信息

try:
s = raw_input("Enter Something:")
print s
print "Done"
except EOFError:
print "\nWhy did you do an EOFError on me?" #当发生'EOFError'时执行此语句
except:
print "\nsome error/exception occurred." #当发生其他类型异常时统统执行此语句

输出:重读LPTHW-Lesson37

重读LPTHW-Lesson37

11.exec

exec语句用来执行储存在字符串或文件中的Python语句。

>>> exec "print 'Hello World!'"
Hello World!

12.in

for...in...语句;xx in [...]语句

13.lambda

lambda定义匿名函数。lambda定义函数仅一行语句。它只需要一个参数,后面紧跟单个表达式作为函数体,并返回表达式的值。需要注意的是,lambda只能跟表达式。

>>> s = lambda x:x ** 3      #定义匿名函数,求三次方
>>> s(3)
27
>>> s(5)
125
>>>

14.raise语句用来引发异常。需要知名错误/异常的名称和伴随异常触发的异常对象,可以引发的错误或异常应该分别是一个Error或Exception的类的导出类。

# -*- coding:utf-8 -*-
class ShortInputError(Exception):
def __init__(self,length,atleast):
Exception.__init__ 初始化
self.length = length
self.atleast = atleast
try:
s = raw_input("Enter something:")
if len(s) < 3:
raise ShortInputError(len(s),3)
except EOFError:
print '\nWhy did you do an EOF on me?'
except ShortInputError,x:
print 'ShortInputError:The input was of length %d,\
was expecting at least %d' %(x.length,x.atleast)
else:
print "No exception was raised."

输出:重读LPTHW-Lesson37

重读LPTHW-Lesson37