List of Keywords in Python

英文原文:https://www.programiz.com/python-programming/keyword-list

下面介绍Python中所有关键字的概要信息。

"关键字"是Python中的保留字。我们不能用关键字来命名变量名、函数名或其它标识符。

Keywords in Python programming language
False class finally is return
None continue for lambda try
True def from nonlocal while
and del global not with
as elif if or yield
assert else import pass  
break except in raise  

上面的关键字,在Python不同的版本中可能会有所不同。有的可能会添加一些额外的内容,有的可能会删除一些东西。

不过我们可以通过下面的代码,获得我们使用的版本中的关键字列表。

import keyword

print(keyword.kwlist)

会打印出所有的关键字。

Python中关键字的描述及相关例子

True、False

True和False是Python中的真值。在Ptyhon中,True和False是"比较操作"或"逻辑(布尔)操作"的结果。

print(1==1)  #结果为True
print(5 > 3) #结果为True
print(True or False) #结果为True
print(True and False) #结果为False 

我们可以看到,前3个语句是正确的,所以编译器返回True。最后一个是错误的,所以返回False。

在Python中,True或False和1和0一样,可以通过如下证明:

print(True == 1)  #结果为True
print(False == 0)  #结果为True
print(True + False) #结果为1

None

在Python中,None是一个特殊的常量,表示不存在的值或者空值。

它是自己数据类型的对象,NoneType。我们不能创建None对象,但我们可以把None分配给多个变量,这些变量彼此相等。

我们必须注意,None不代表着False、0或其它空(list、dictionary、string等等)。举例:

print(None == 0)  #结果为False
print(None == []) #结果为False
print(None == False) #结果为False
x = None;
y = None;

print( x == y) ;#结果为True

不返回任何内容的虚函数将自动返回一个None对象。None也由程序流未遇到return语句的函数返回。

(None is also returned by functions in which the program flow does not encounter a return statement)。举例:

def a_void_function():
    a = 1;
    b = 2;
    c = a + b;

x = a_void_function();

print(x);

#结果为 3 (错误答案)
#结果为 None(Yes)

这段代码有一个不返回值的函数,尽管该函数内部做了一些操作。

但我们打印x 的时候,我们得到了一个自动(隐式)返回的None。同样的,这是另一个例子:

def improper_return_function(a):
    if(a % 2 == 0):
        return True;

x = improper_return_function(3);

print(x)

#结果为None

如果我们给这个函数一个偶数,则返回True;如果我们给一个奇数,则该函数隐式的返回None。

and,or,not

在Python中,"and,or,not"是逻辑操作。只有当and连接的两个操作都是True的时候,and的操作才是True。

True and True  = True

True and False = False

False and True = False

False and True = False

当or连接的两个操作,有任何一个是True的时候,or的操作就是True。

True or True = True

True or False = True

Fasle or True = True

False or False = False

not操作用于反转真值。

not True = False

not False = True

as

as is used to create an alias while importing a module. It means giving a di?erent
name (user-de?ned) to a module while importing it.
As for example, Python has a standard module called  math . Suppose we want to
calculate what cosine pi is using an alias. We can do it as follows using  as :

当我们引入一个模块的时候,可以用as创建一个模块的别名。这意味着,当我们引入一个模块的时候,我们可以给这个模块一个不同的名字(用户自定义的名字)。

例如,Python有一个标准的模块是math。假设我们想使用别名计算一个余弦

import math as myAlias
myAlias.cos(myAlias.pi)

#结果为 -1.0

assert

assert用于debug。

在编程时,有时我们想知道内部状态或者检查下我们的假设是不是正确,assert可以帮助我们做到这些并且可以更方便的发现bug。

assert后面都会跟着一个条件。如果条件是真的,什么也不会发生。如果条件是错的,会报AssertionError

a = 4
assert a < 6 #不会有报错,也不会有提示
assert a > 10
#会报错
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
AssertionError

为了更好的理解,我们也可以提供一条与AssertionError一起打印的信息

a = 4

assert a > 5, "The value of a is too small"

#会报错
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
AssertionError: The value of a is too small

我们可以标记下:

assert condition, message

等同于:

if not condition:
    raise AssertError(message);

break,continue

break和continue被用在for循环或者while循环中,用来改变循环的正常流程。

break用来结束它所在的最小循环并且控制程序要立即执行循环下面的语句。

continue用来结束当前循环,继续下一次循环。而不是结束整个循环。

下面用两个例子说明:

for i in range(1,11):
    if i == 5:
        break;

    print(i)

最终输出的只有:1,2,3,4 

在这个程序里,for循环本来是要将数字从1到10打印出来。但是当i = 5的时候,我们执行了break,循环结束了。

所以,我们仅仅打印了数字1到4。

for i in range(1,11):
    if i == 5:
        continue;
    
    print(i);

最终的输出结果:1,2,3,4,  6,7,8,9,10。没有打印5。

在同样的程序里,我们用了continue。所以,当i=5的时候,本次循环被跳过,继续下次循环。

但我们没有退出循环。因此,除了5之外的数字都被打印出来了。

要学习更多的关于break和continue的话,参考(https://www.programiz.com/python-programming/break-continue

class

在Python中,class用来定义一个用户自定义的类。

类是一个相关属性和方法的集合,这些属性和方法试图表现真实的世界。

将数据和函数放在一个类型的想法,是面向对象编程(OOP)的中心思想。

类可以在程序的任何地方定义。但是在一个模块中定义一个类是很好的实践。下面是一个示例用法:

class ExampleClass:
    def function1(parameters):
        ...
    def function2(parameters):
        ...

可以在链接中学习更多(https://www.programiz.com/python-programming/class

def

def用来定义一个用户自定义的函数。

函数,是一个相关语句块,它们一起执行一些特殊的任务。函数帮助我们将代码组织成可以管理的块,并可以执行一些重复的任务。

def function_name(parameters):
    ....

想学习更多,参考(https://www.programiz.com/python-programming/function

del

用del删除一个对象的引用。在Python中,万物皆对象。我们可以用del删除一个变量的引用。

a = b = 5;

del a;
print(a)

#会报错
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    print(a)
NameError: name 'a' is not defined

print(b) #正常显示:5

del也可以用来删除list或dictionary中的元素:

a = [1,2,3,4,5]

del a[2]

print(a)

#结果为[1,2,4,5]

if, else, elif

我们用if,else,elif来做条件分支或者做决策。

 

当我们想测试某些条件,在只有条件成立时才执行一个代码块时,我们用 if 和 elif。elif 是else if的简写。

当条件是False的时候,else代码块才被执行。

def if_example(a):
    if a==1:
        print('One')
    elif a==2:
        print('Two')
    else:
        print('Else')

if_example(3)

#结果是打印 Else

当输入的数字是1或2的时候,这个函数会打印One或Two。

其它的输入,会导致else 代码块的执行。

想学习更多,参考(https://www.programiz.com/python-programming/if-elif-else

except, raise, try

在Python中,except、raise、try用于异常的处理。

异常基本上是指当程序运行时出现的问题。一些简单的异常如:(IOError ,  ValueError ,  ZeroDivisionError ,  ImportError ,  NameError ,TypeError等等)。try...except用来捕获Python中的异常。

def reciprocal(num):
    try:
        r = 1/num;
    except:
        print('Exception caught')
        return

    return r

reciprocal(10) #结果为0
reciprocal(0) #结果为 Exception caught

x = reciprocal(0) #这行会报错 Exception caught

print x #打印None

这是一个ZeroDivisionError错误。

我们也可以用raise关键字显式地引发异常。

if num == 0 :
    raise ZeroDivisionError('cannot divide')

finally

finally和try…except一起用,用以关闭资源或文件流。

Using  finally ensures that the block of code inside it gets executed even if there
is an unhandled exception。(使用finally 来确保:即使程序出现了处理不了的异常,finally块里的代码仍然能被执行)

try:
    Try-block
except exception1:
    Exception1-block
except exception2:
    Exception2-block
else:
    Else-block
finally:
    Finally-block

如果Try-block出现了异常,会在except 或者else块里处理。

但是不管执行的顺序是什么,我们可以保证Finally-block的代码一定会执行,即使处理过程中出现了错误。Finally代码块对清理资源很有用。

想了解更多,参考(https://www.programiz.com/python-programming/exception-handling

for

for关键字用于循环。当我们知道循环次数时,我们可以用for关键字。

在Python中,for循环可以搭配任何类型的序列,比如数组和字符串。下面是一个示例,for 用于遍历一个名称列表:

names = ['One','Two','Three','Four']

for i in names :
    print i

#结果是
One
Two
Three
Four

想了解更多,参考(https://www.programiz.com/python-programming/for-loop

from, import

import keyword is used to import modules into the current namespace.  from…
import is used to import speci?c attributes or functions into the current
namespace. For example:

关键字import 用于将模块导入当前命名空间。

import math

我们将引入math模块。现在我们可以在代码里通过math.cos() 使用math模块的cos() 函数。但是如果我们仅仅需要cos() 函数,不需要其它函数,可以用 from  关键字做到

from math import cos

现在我们仅仅能用cos() 函数了,并且可以直接使用cos() 函数做运算。不用再写math.cos() 了。

想了解更多,参考(https://www.programiz.com/python-programming/modules

global

global用于声明函数内部的变量是全局的(函数外部)。如果我们只是读取全局变量的值,那么我们没有必要将其定义为全局变量。这是可以理解的。

如果我们在一个函数中要修改全局变量的值,那么我们必须使用global关键字进行定义,否则将创建名称相同的局部变量。

举例:

globvar = 10;

def read():
    print(globvar)

def write1():
    global globvar
    globvar = 5

def write2():
    globvar = 100  #没有用global定义,这就是创建了一个名称相同的本地变量

read()
#结果是10
write1()
read()
#结果是5

write2()
read()
#结果是5  (注意,结果不是100)

上面的代码中,read() 函数的功能是读取globvar 变量的值。所以,我们不需要使用global关键字,也不需要声明一个global 变量,直接读取globvar变量的值即可。

但是在write1() 函数中,要修改globvar变量的值,所以我们需要声明一个global变量。在输出结果里可以看到,write1() 函数的修改起作用了(10变成5了)。

write2() 函数也是尝试着修改globvar变量的值,但我们没有将其声明为全局变量,因此,一个本地变量globvar被创造出来了。这个本地变量在write2() 函数外是不可见的。尽管我们将这个本地变量修改为15,但是全局变量保持不变。这在我们的输出中非常清晰。

in

我们用in 关键字来测试一个序列(list、tuple、string等)是否包含某值。如果值存在,则返回True,否则返回False。举例:

a = [1,2,3,4,5]
5 in a   # 结果为True

10 in a   # 结果为False

第二种用途是遍历for 循环中的序列:

for i in 'Hello':
    print(i)


# 结果为:
H
e
l
l
o

is

Python中关键字is是测试对象标识的。"=="操作符时比较两个变量是否相等,"is"是用来比较两个变量是否引用同一个对象。

如果对象相同则返回True,如果不同则返回False。

True is True
#结果为True

False is False 
#结果为True

None is None
#结果为True

我们知道在Python中,只有一个True、Flase和None的实例,所以他们是完全相同的。

当然  True is None,结果是False。

[] == []
#结果是True

[] is []
#结果是 False

{} == {}
#结果是True

{} is {}
#结果是 False

An empty list or dictionary is equal to another empty one. But they are not
identical objects as they are located separately in memory. This is because list and
dictionary are mutable (value can be changed).

一个空的列表或者空的字典是相等的。但他们不是完全一样的对象,因为它们在内存中是分别存放的。

(列表和字典的值是可变的,要结合元祖值不可变理解)

'' == ''
#结果是True

'' is ''
#结果是True

() == ()
#结果是True

() is ()
#结果是True

不像数组或者字典,字符串和元祖是不变的(只要被定义,则字符串和元祖的值不可变)。

因此,两个相等的字符串或元祖也是相同的。他们指向相同的内存地址。

lambda

关键字lambda用于创建一个匿名函数(没有名字的函数)。它是一个不包含return语句的内联函数。它由计算并返回的表达式组成。

a = lambda x: x*2
for i in range(1,6):
    print(a(i))

结果是:2,4,6,8,10

在代码里,我们用lambda关键字创建了一个匿名函数:将值乘以2。

后面我们将数字1到5的值扩大了两倍,然后打印出来。
想了解更多,参考(https://www.programiz.com/python-programming/anonymous-function

nonlocal

非本地(非局部)变量的使用和全局变量的使用非常类似。

关键字nonlocal,用于在嵌套函数(函数里面的函数)中声明非局部变量,这意味着它位于外部包含函数中。

如果我们需要在嵌套函数中修改非局部变量的值,我们必须使用nonlocal来声明它。否则我们会在嵌套函数内部创建一个同名的局部变量。

def outer():
    x = "local"
 
    def inner():
        nonlocal x
        x = "nonlocal"
        print("inner:", x)
 
    inner()
    print("outer:", x)
 
outer()

结果是: inner:nonlocal,outer:nonlocal

上面的代码中,inner()函数被嵌套在outer()函数中。

outer()函数中有一个变量x 。所以,如果我们想在inner() 函数中修改它的值,我们必须用关键字nonlocal 声明它。(注意,outer()函数中的x 变量并不是全局变量。inner()函数中也不需要用global声明变量x)。

(注意:在inner() 函数中,可以直接获取outer() 函数定义的变量x),举例:

def outer():
    x = 100
    def inner():
        print(x)


outer()

#结果是100
   

因此,从结果中我们看到,inner() 函数成功修改了x 的值。但如果我们在inner() 函数中不用关键字nonlocal 进行声明呢?这将是另一个故事了:

def outer():
    x = 100

    def inner():
        x = 9999
        print("inner: ",x)
    
    print("outer: ",x)

outer()

#结果是 inner: 9999,outer: 100

在嵌套函数inner() 中我们没有用 nonocal关键字声明变量x。因此,一个新的本地变量被创建,虽然名字和x相同。但是在结果中我们看到,inner() 函数并没有修改outer()函数中x的值。outer()函数中x仍然是100。

pass

pass是Python中的空语句。当执行pass时,什么也没有发生。它的作用就像一个占位符。

假设我们有一个未完成的函数,但我们想在将来写完这个函数,我们可以简写为:

def function(args):
    

在程序中间会给我们一个IndentationError(缩进错误)。相反,我们可以用pass语句创建一个空主体。

def function(args):
    pass

我们在定义类的时候也可以这么写:

class example:
    pass

return

在函数中使用return语句,用于结束函数并且返回一个值。

如果我们不明确的返回一个值,就会自动返回None。例子:

def    func_return():
    a = 10
    return a

def no_return():
    a = 100

print(func_return())
#打印10

print(no_return())
#打印None

while

while用于处理Python中的循环。

while循环中的语句继续执行,直到while循环的条件计算为False或遇到break语句为止。

i = 3
while(i):
    print(i)
    i = i - 1 

结果是:3,2,1

注意:0等于False。 

了解更多,参考(https://www.programiz.com/python-programming/while-loop

with

with statement is used to wrap the execution of a block of code within methods
defined by the context manager.( with语句用于在上下文管理器定义的方法中包装代码块的执行)
Context manager is a class that implements  __enter__ and  __exit__ methods.(上下文管理器是一个类,实现了 __enter__ 和 __exit__ 的方法)。 Use of  with statement ensures that the  __exit__ method is called at the end of the
nested block. ( 使用with语句确保在嵌套块结束时调用 __exit__  方法。)This concept is similar to the use of  try…finally block.(这个概念和使用try...finally语句块非常相似)。

with open('example.txt', 'w') as my_file:
    my_file.write('Hello world!')

感觉这种代码没啥用呢~~

This example writes the text  Hello world! to the file  example.txt . File objects have __enter__ and  __exit__ method defined within them, so they act as their own context manager.
First the  __enter__ method is called, then the code within  with statement is executed and ?nally the  __exit__ method is called.  __exit__ method is called even if there is an error.

It basically closes the file stream.

yield

(没弄明白)

yield is used inside a function like a  return statement. But  yield returns a generator.

Generator is an iterator that generates one item at a time. A large list of value will take up a lot of memory. Generators are useful in this situation as it generates only one value at a time instead of storing all the values in memory.

g = (2**x for x in range(100))

will create a generator  g which generates powers of 2 up to the number two raised to the power 99. We can generate the numbers using the  next() function as shown below.

next(g) #结果是1

next(g) #结果是2

next(g) #结果是4

next(g) #结果是8

...

And so on… This type of generator is returned by the  yield statement from a function.

def generator():
    for i in range(6):
        yield i*i

g = generator()

for i in g:
    print(i)

结果是:

0  
1
4
9
16
25

Here, the function  generator() returns a generator that generates square of numbers from 0 to 5. This is printed in the  for loop.

发布了57 篇原创文章 · 获赞 20 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/shafatutu/article/details/103630294