Python 中的关键字

pythonprogrammingserver side programming更新于 2024/3/27 9:28:00

与其他语言一样,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

输出

True
False

class、def、return 关键字

在 Python 中,class 关键字用于定义新的用户定义类。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 块中,我们可以编写一些代码,这些代码可能会 引发 一些异常,而使用 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 关键字用于检查某些元素是否参与某些容器对象。还有另外两个关键字,分别是 isnotis 关键字用于测试对象的身份。 not 关键字用于反转任何条件语句。

示例代码

#关键字 for、in、is、not
animal_list = ['Tiger', 'Dog', 'Lion', 'Peacock', 'Snake']
    for animal in animal_list: #遍历 animal_list 中的所有动物
    if animal is 'Peacock': #使用 'is' 关键字进行相等性检查
        print(animal + ' is a bird')
    elif animal is not 'Snake': #使用 'not' 关键字进行否定性检查
        print(animal + ' is animal')

输出

Tiger 是哺乳动物
Dog 是哺乳动物
Lion 是哺乳动物
Peacock 是鸟

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

相关文章