Python keywords, also known as reserved words.

Reserved words are officially defined words with a particular meaning. Users cannot use reserved words as customized names of variables, functions, and classes.

View the current Python version of the reserved word method.

Open CMD, run Python, and enter Python interactive mode

Then enter the following code in sequence:

>>> import keyword
>>> Keyword. Kwlist Output: ['False'.'None'.'True'.'and'.'as'.'assert'.'async'.'await'.'break'.'class'.'continue'.'def'.'del'.'elif'.'else'.'except'.'finally'.'for'.'from'.'global'.'if'.'import'.'in'.'is'.'lambda'.'nonlocal'.'not'.'or'.'pass'.'raise'.'return'.'try'.'while'.'with'.'yield']
Copy the code

The following output is a list of reserved words.

Each reserved word is described next.


False

Boolean value, indicating false. Equivalent to 0, as opposed to True

print(1>2)
print(5 > 6)
print(4 in [1.2.3])
print("hello" is "goodbye")
print(5= =6)
print(5= =6 or 6= =7)
print(5= =6 and 6= =7)
print("hello" is not "hello")
print(not(5= =5))
print(3 not in [1.2.3])
Copy the code
None

Define null to indicate that there is no value at all.

x = None
print(x)
Copy the code

Note: 0,False, “” is null, but not None. None means nothing except None=None, right

True

Boolean value for true. Equivalent to 1, as opposed to False

and,or

And is used to join two statements, True if both are True.

Or is used to join two statements, True if either of them is True

a=1
b=2
if a==1 and b==2:
    print("OK") # OK
if a==1 or b==3:
    print("OK") # OK
Copy the code
as

Create an alias.

import os as a After importing the OS, create an alias for the OS
print(a.getcwd())
Copy the code
assert

Used when debugging code and continues if the given condition is True. If False, an AssertionError is raised.

x = "hello"

# if the condition returns True, nothing happens:
assert x == "hello"

AssertionError is raised if the condition returns False:
assert x == "goodbye"
Copy the code
Break with the continue

Break Breaks the current loop body.

for i in range(1.10) :if i == 5:
        break No output after 4
    print(i)
Copy the code

Continue skips the end of the loop without executing the rest of the loop.

for i in range(1.10) :if i == 5:
        continue Do not print 5
    print(i)
Copy the code
class

Define a class.

class Rect() :
    "" defines a rectangle class """
    def GetArea(self, x, y) :
        """
        获取矩形面积
        """
        return x*y
Copy the code
def

Define a function

def add(x,y) :
    return x+y
Copy the code
del

Undefine an object. It can be a class, variable, or function

del Rect
del add
Copy the code
if,elif,else

If evaluates a condition; if true, it continues; if not, it jumps to elif or else.

Elif The condition that if does not meet can be further judged

Else executes on conditions that neither if nor elif satisfies

a = -1
if a>0:
    print("A is positive.")
elif a<0:
    print("A is negative.")
else:
    print("A is zero")
Copy the code
try,except,finally,raise

Exception handling in Python. Determine what to do when a program goes wrong

Raise is used to raise an error.

try:
    x = 0
    # b = 100 / x # raises a ZeroDivisionError
    if x == 0:
        raise Exception("The divisor cannot be zero.") Raise a custom error. Exception
except ZeroDivisionError as e:
    print("An exception has occurred!", e)
except Exception as e:
    print("An exception has occurred!", e)
finally:
    print("This code is going to execute anyway.")
Copy the code
for,in,while

The for loop

for i in range(1.10) :print(i)
Copy the code

The while loop

count = 10
while count > 0:
    print(count)
    count=count-1
Copy the code
import,from

Import Import module

From imports specific parts from a module.

from datetime import time
Import only the time section from the datetime module
x = time(hour=15)

print(x)
Copy the code
global

Defines a global variable that can be defined in a function

def calc() :
    global xxaa
    xxaa = 1000

calc()
print(xxaa)
Copy the code
is

Tests whether two variables refer to the same object

Note that the judgment is that two variables refer to the same object.

Return false if only the value is the same.

a = ["a"."b"."c"]
c = ["a"."b"."c"]
b = a
print(a is b) # True
print(c is a or c is b) # False
Copy the code
lambda

Use to create a small anonymous function.

func = lambda a,b: a+b
print(func(1.2)) # 3
Copy the code
nonlocal

Used inside a nested function to indicate that the current variable belongs to the function at the previous level.

def FuncA() :
    aaa = 100
    def FuncB() :
        nonlocal aaa If nonlocal is not added, aaa becomes local to the function
        aaa = 999
    FuncB()
    return aaa

print(FuncA())
Copy the code
not

Invert. Returns True if False

print(not True) # False
print(not 0) # True
print(not "a") # False
Copy the code
pass

Placeholder to prevent syntax check errors

if True: 
    passNo error will be reported

if True: # Nothing below will cause an error
Copy the code
return

Return: indicates that the current function is completed and the next line of code in return is ignored.

def FuncA() :
    print(1)
    print(2)
    return 0
    print(3) # not implemented
FuncA()
Copy the code
with

To simplify error handling, that is: try… . Except… .finlally

Need to complete __enter__,__exit__ method, more usage please refer to Baidu.

class Test() :
    def __init__(self) :
        print("Init is called.")
    def __enter__(self) :
        print("Enter calls")
        return self
    def myFunc(self) :
        print(XVZ()) # raise an exception
    def __exit__(self,exc_type,exc_value,exc_trackback) :
        print("Exit call")
        print(exc_type,exc_value,exc_trackback)
        
with Test() asT: t.myfunc () : init is called enter call exit call <class 'NameError'> name 'XVZ' is not defined <traceback object at 0x046C7B08>
Traceback (most recent call last) :. Attention! The program exits with an error, but __exit__ has been executed, equivalent tofinally
Copy the code
yield

Example use complex, please click: blog.csdn.net/mieleizhi05…

Async and await

Please refer to baidu for information on asynchronous execution and generators.

If this article has been helpful to you, please reply and make this post available to more people.