Every programming language has some special words called keywords. The basic requirement to treat keywords is to avoid repetition when naming them. This article introduces the keywords in Python. Keywords are not built-in functions or built-in object types. Although it's better not to rename them, you can also use names that are the same as built-in functions or built-in object types. Keywords are different. They are not allowed.
In Python 3.8, 35 keywords are provided as follows:
False await else import pass
None break except in raise
True class finally is return
and continue for lambda try
as def from nonlocal while
assert del global not with
async elif if or yield
If you want to view keywords in interactive mode, you can use help():
>>> help("keywords") Here is a list of the Python keywords. Enter any keyword to get more help. False await else import pass None break except in raise True class finally is return and continue for lambda try as def from nonlocal while assert del global not with async elif if or yield
For a detailed description of each keyword, you can also use help() to view:
>>> help('pass') # The following appears after you tap enter The "pass" statement ******************** pass_stmt ::= "pass" "pass" is a null operation — when it is executed, nothing happens. It is useful as a placeholder when a statement is required syntactically, but no code needs to be executed, for example: def f(arg): pass # a function that does nothing (yet) class C: pass # a class with no methods (yet)
In addition to the above methods, there is a standard library module keyword which provides keyword query function.
>>> import keyword >>> keyword.kwlist ['False', 'None', 'True', 'and', 'as', 'assert', 'async', ... >>> len(keyword.kwlist) 35
So, how to use these keywords? In what scenarios? Some key words are described in the following example.
True, False, and None
True and False are two values of boolean type, note that they must be capitalized.
>>> x = True >>> x is True True >>> y = False >>> y is False True
If we want to determine whether the Boolean value of an object is True or False, we can use the bool() function, for example:
>>> x = "this is a truthy value" >>> x is True False >>> bool(x) is True True >>> y = "" # This is fake >>> y is False False >>> bool(y) is False True
Note that if the parameter passed in to bool() is 0, any one of '', {}, [], the return value is False.
In conditional statements, it is supposed to judge whether the condition is True or not. However, it is usually not necessary to directly compare it with True or False, relying on Python parser to automatically judge the condition.
>>> x = "this is a truthy value" >>> if x is True: # Don't do that ... print("x is True") ... >>> if x: # It should be ... print("x is truthy") ... x is truthy
The keyword "None" means no value in Python. In other languages, the same meaning may be null,nil,none,undef,undefined, etc. None is also the default return value when there is no return statement in the function.
>>> def func(): ... print("hello") ... >>> x = func() hello >>> print(x) None
and,or,not,in,is
These keywords, in fact, correspond to operators in mathematics, as shown in the following table.
Mathematical symbols | key word |
---|---|
AND, ∧ | and |
OR, ∨ | or |
NOT, ¬ | not |
CONTAINS, ∈ | in |
IDENTITY | is |
Python code has a strong readability. You can know what operation is at a glance through keywords.
These key words are easy to understand. Here we just remind you that there is a famous short circuit operation in Python, such as and:
<expr1> and <expr2>
Don't interpret the above formula as returning True when both sides are True. For this, please refer to the book "practical course of Python University". The other is or, which also has short circuit operation.
break, continue and else
These are the keywords that are often used in loop statements.
The function of break is to terminate the current loop. It uses the basic format:
for <element> in <container>: if <expr>: break //for instance: >>> nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> sum = 0 >>> for num in nums: ... sum += num ... if sum > 10: ... break ... >>> sum 15
Continue is to skip some loops and let them continue.
for <element> in <container>: if <expr>: continue
else is in the conditional statement. It is mentioned here. It is in the loop statement. Its function is to continue executing code when the loop ends.
In the for loop, use the following format:
for <element> in <container>: <statements> else: <statements>
In the while loop, use the following format:
while <expr>: <statements> else: <statements>
For example, sometimes we use a flag variable in a loop statement:
>>> for n in range(2, 10): ... prime = True ... for x in range(2, n): ... if n % x == 0: ... prime = False ... print(f"{n} is not prime") ... break ... if prime: ... print(f"{n} is prime!") ... 2 is prime! 3 is prime! 4 is not prime 5 is prime! 6 is not prime 7 is prime! 8 is not prime 9 is not prime
In the above code, prime is a flag variable. If the loop ends normally, the value of prime is True. Otherwise, it is False. If you exit from the loop, line 8 determines the value of this variable, and if it is True, the corresponding content will be printed.
For the above code, if you rewrite it with else, it can be simpler and more readable.
>>> for n in range(2, 10): ... for x in range(2, n): ... if n % x == 0: ... print(f"{n} is not prime") ... break ... else: ... print(f"{n} is prime!") ... 2 is prime! 3 is prime! 4 is not prime 5 is prime! 6 is not prime 7 is prime! 8 is not prime 9 is not prime