Python中常见关键字及其用法介绍

Python中常见关键字及其用法介绍_第1张图片

这篇文章主要介绍了Python中有哪些关键字及关键字的用法,分享python中常用的关键字,本文结合示例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

Python有哪些关键字

Python常用的关键字

1

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

删除变量

1

2

3

4

5

6

7

8

9

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)

而列表本身包含的是变量,例:

1

2

3

list = [1,2,3]

# 包含list[0],list[1],list[2]

# 并不包含数字1,2,3

所以

1

2

3

4

5

6

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引用模块时会用到,例:

1

2

3

4

5

6

7

from sys import argv

# 从sys中导入argv

from sys import *

# 将sys中所有东西都导入

import sys

# 导入sys,当需要sys中内容时,需sys.argv而from sys import *

#不用每次都重复输入'sys.'

4.golbal

golbal为全局变量,但当单个函数中出现同一变量名时,在单个函数中为局部变量

1

2

3

4

5

6

7

8

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 处理文件异常

1

2

3

4

5

file = open("/tmp/foo.txt")

try:

    data = file.read()

finally:

    file.close()

  • 用with

1

2

3

with open("/tmp/foo.txt")

 as file:

    data = file.read()

紧跟with后面的语句被求值后,返回对象的enter()方法被调用,这个方法的返回值将被赋值给as后面的变量,此处为file
当with后面的代码块全部被执行完后,将调用前面返回对象的exit()方法

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

#with 的工作     

class Sample:

    def __enter__(self):

        print ("In __enter__()")

     

你可能感兴趣的:(编程语言,Python,python,开发语言)