Python 关键字
像其他语言一样,Python 也有一些保留字。这些单词具有一些特殊含义。有时它可能是一个命令,或一个参数等。我们不能将关键字用作变量名。
Python 关键字如下:
True | False | class | def | return |
if | elif | else | try | except |
raise | finally | for | in | is |
not | from | import | global | lambda |
nonlocal | pass | while | break | continue |
and | with | as | yield | del |
or | assert | None |
True & False 关键字
True 和 False 是 Python 中的真值。比较运算符返回 True 或 False。布尔变量也可以保存它们。
示例代码
#Keywords True, False print(5 < 10) #it is true print(15 < 10) #it is false
Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.
输出
True False
class、def、return 关键字
class 关键字用于在 Python 中定义新的用户自定义类。def 用于定义用户自定义函数。return 关键字用于从函数返回并向调用函数发送值。
示例代码
#Keywords Class, def, return class Point: #Class keyword to define class def __init__(self, x, y): #def keyword to define function self.x = x self.y = y def __str__(self): return '({},{})'.format(self.x, self.y) #return Keyword for returning p1 = Point(10, 20) p2 = Point(5, 7) print('Points are: ' + str(p1) + ' and ' + str(p2))
输出
Points are: (10,20) and (5,7)
if、elif、else 关键字
这三个关键字用于条件分支或决策。当 if 语句的条件为真时,它进入 if 代码块。当它为假时,它搜索另一个条件,因此如果有一些 elif 代码块,它会用它们检查条件。最后,当所有条件都为假时,它进入 else 部分。
示例代码
#Keywords if, elif, else defif_elif_else(x): if x < 0: print('x is negative') elif x == 0: print('x is 0') else: print('x is positive') if_elif_else(12) if_elif_else(-9) if_elif_else(0)
输出
x is positive x is negative x is 0
try、except、raise、finally 关键字
这些关键字用于处理 Python 中的不同异常。在 try 代码块中,我们可以编写一些代码,这些代码可能会 raise 一些异常,并使用 except 代码块来处理它们。即使存在未处理的异常,finally 代码块也会执行。
示例代码
#Keywords try, except, raise, finally defreci(x): if x == 0: raise ZeroDivisionError('Cannot divide by zero') #raise an exception else: return 1/x deftry_block_example(x): result = 'Unable to determine' #initialize try: #try to do next tasks result = reci(x) except ZeroDivisionError: #except the ZeroDivisionError print('Invalid number') finally: # Always execute the finally block print(result) try_block_example(15) try_block_example(0)
输出
0.06666666666666667 Invalid number Unable to determine
for、in、is、not 关键字
for 关键字基本上是 Python 中的 for 循环。in 关键字用于检查某个元素在某些容器对象中的参与情况。还有另外两个关键字,分别是 is 和 not。is 关键字用于测试对象的标识。not 关键字用于反转任何条件语句。
示例代码
#Keywords for, in, is, not animal_list = ['Tiger', 'Dog', 'Lion', 'Peacock', 'Snake'] for animal in animal_list: #iterate through all animals in animal_list if animal is 'Peacock': #equality checking using 'is' keyword print(animal + ' is a bird') elif animal is not 'Snake': #negation checking using 'not' keyword print(animal + ' is mammal')
输出
Tiger is mammal Dog is mammal Lion is mammal Peacock is a bird
from、import 关键字
import 关键字用于将某些模块导入到当前命名空间中。from…import 用于从模块导入一些特殊属性。
示例代码
#Keywords from, import from math import factorial print(factorial(12))
输出
479001600
global 关键字
global 关键字用于表示在代码块内部使用的变量是全局变量。当不存在 global 关键字时,变量将表现为只读。要修改值,我们应该使用 global 关键字。
示例代码
#Keyword global glob_var = 50 defread_global(): print(glob_var) def write_global1(x): global glob_var glob_var = x def write_global2(x): glob_var = x read_global() write_global1(100) read_global() write_global2(150) read_global()
输出
50 100 100
lambda 关键字
lambda 关键字用于创建一些匿名函数。对于匿名函数,没有名称。它就像一个内联函数。匿名函数中没有 return 语句。
示例代码
#Keyword lambda square = lambda x: x**2 for item in range(5, 10): print(square(item))
输出
25 36 49 64 81
nonlocal 关键字
nonlocal 关键字用于声明嵌套函数中的变量不是局部变量。因此,它是外部函数的局部变量,但不是内部函数的局部变量。此关键字用于修改某些非局部变量的值,否则它处于只读模式。
示例代码
#Keyword nonlocal defouter(): x = 50 print('x from outer: ' + str(x)) definner(): nonlocal x x = 100 print('x from inner: ' + str(x)) inner() print('x from outer: ' + str(x)) outer()
输出
x from outer: 50 x from inner: 100 x from outer: 100
pass 关键字
pass 关键字基本上是 Python 中的空语句。当执行 pass 时,什么也不会发生。此关键字用作占位符。
示例代码
#Keyword pass defsample_function(): pass #Not implemented now sample_function()
输出
(No Output will come)
while、break、continue、and 关键字
while 是 Python 中的 while 循环。break 语句用于退出当前循环,控制权移动到紧接在循环下方的部分。continue 用于忽略当前迭代。它移动到不同循环中的下一个迭代。
and 关键字用于 Python 中的逻辑与运算,当两个操作数都为真时,它返回 True 值。
示例代码
#Keywords while, break, continue, and i = 0 while True: i += 1 if i>= 5 and i<= 10: continue #skip the next part elifi == 15: break #Stop the loop print(i)
输出
1 2 3 4 11 12 13 14
with、as 关键字
with 语句用于将一组代码的执行包装在由上下文管理器定义的方法中。as 关键字用于创建别名。
示例代码
#Keyword with, as with open('sampleTextFile.txt', 'r') as my_file: print(my_file.read())
输出
Test File. We can store different contents in this file ~!@#$%^&*()_+/*-+\][{}|:;"'<.>/,'"]
yield 关键字
yield 关键字用于返回生成器。生成器是一个迭代器。它一次生成一个元素。
示例代码
#Keyword yield defsquare_generator(x, y): for i in range(x, y): yield i*i my_gen = square_generator(5, 10) for sq in my_gen: print(sq)
输出
25 36 49 64 81
del、or 关键字
del 关键字用于删除对象的引用。or 关键字执行逻辑或运算。当至少一个操作数为真时,答案将为真。
示例代码
#Keywords del, or my_list = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110] index = [] for i in range(len(my_list)): if my_list[i] == 30 or my_list[i] == 60: index.append(i) for item in index: del my_list[item] print(my_list)
输出
[10, 20, 40, 50, 60, 80, 90, 100, 110]
assert 关键字
assert 语句用于调试。当我们想要检查内部状态时,可以使用 assert 语句。当条件为真时,它不返回任何内容,但当它为假时,assert 语句将引发 AssertionError。
示例代码
#Keyword assert val = 10 assert val > 100
输出
--------------------------------------------------------------------------- AssertionErrorTraceback (most recent call last) <ipython-input-12-03fe88d4d26b> in <module>() 1#Keyword assert 2val=10 ----> 3assertval>100 AssertionError:
None 关键字
None 是 Python 中的一个特殊常量。它表示空值或值缺失。我们不能创建多个 none 对象,但可以将其分配给不同的变量。
示例代码
#Keyword None deftest_function(): #This function will return None print('Hello') x = test_function() print(x)
输出
Hello None