Python有哪些关键字
Python常用的关键字
文中有不理解的地方,可以点击文末名片进行交流学习~
and, del, from, not, while, as, elif, global, or, with, assert, else, if, pass, yield, break, except, import, print, class, exec, in, raise, contiue, finally, is, return, def, for, lambda, try
1.and , or
and , or 为逻辑关系用语,Python具有短路逻辑,False and 返回 False
不执行后面的语句, True or 直接返回True,不执行后面的语句
2.del
删除变量
if __name__=='__main__':
a=1 # 对象 1 被 变量a引用,对象1的引用计数器为1
b=a # 对象1 被变量b引用,对象1的引用计数器加1
c=a #1对象1 被变量c引用,对象1的引用计数器加1
del a #删除变量a,解除a对1的引用
del b #删除变量b,解除b对1的引用
#print a #运行此句出错,name 'a' is not defined,说明 del 删除变量a
print(c) #最终变量c仍然引用1
print (c)
而列表本身包含的是变量,例:
list = [1,2,3]
# 包含list[0],list[1],list[2]
# 并不包含数字1,2,3
所以
if __name__=='__main__':
li=[1,2,3,4,5] #列表本身不包含数据1,2,3,4,5,而是包含变量:li[0] li[1] li[2] li[3] li[4]
first=li[0] #拷贝列表,也不会有数据对象的复制,而是创建新的变量引用
del li[0] # 列表本身包含的是变量,del 删除的是变量。
print (li) #输出[2, 3, 4, 5]
print(first) #输出 1
3.from
from引用模块时会用到,例:
from sys import argv
# 从sys中导入argv
from sys import *
# 将sys中所有东西都导入
import sys
# 导入sys,当需要sys中内容时,需sys.argv而from sys import *
#不用每次都重复输入'sys.'
4.golbal
golbal为全局变量,但当单个函数中出现同一变量名时,在单个函数中为局部变量
golbal q
q = 66
print ("q=", q) #q = 66
def function():
q = 3
print ('q =',q)
function() # q = 3
print ('q =',q) # q = 66
5.with
with被用来处理异常
不用with 处理文件异常
file = open("/tmp/foo.txt")
try:
data = file.read()
finally:
file.close()
用with
with open("/tmp/foo.txt")
as file:
data = file.read()
紧跟with后面的语句被求值后,返回对象的enter()方法被调用,这个方法的返回值将被赋值给as后面的变量,此处为file
当with后面的代码块全部被执行完后,将调用前面返回对象的exit()方法
#with 的工作
class Sample:
def __enter__(self):
print ("In __enter__()")
return "Foo"
def __exit__(self, type, value, trace):
print ("In __exit__()")
def get_sample():
return Sample()
with get_sample() as sample:
print (