Python中的关键字
像其他语言一样,Python也有一些保留字。这些词有一些特殊的含义。有时可能是命令或参数等。我们不能将关键字用作变量名。
Python关键字是
正确与错误关键字
True和False是Python中的true值。比较运算符返回True或False。布尔变量也可以保存它们。
范例程式码
现场演示
#Keywords True, False print(5 < 10) #it is true print(15 < 10) #it is false
输出结果
True False
类,def,返回关键字
类关键字被用于在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语句的条件为true,则进入if块。如果为假,它将搜索另一个条件,因此,如果有一些elif块,它将与它们一起检查条件。最后,当所有条件都为假时,它将进入其他部分。
范例程式码
#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
尝试,除了,最终提高
这些关键字用于处理Python中的不同异常。在try块中,我们可以编写一些代码,这可能会引发一些异常,并且可以使用except块来处理它们。在最后即使有未处理的异常块被执行。
范例程式码
#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关键字
在为关键字基本上是在Python中循环。并且在关键字用于检查一些元件的参与一些容器对象。还有另外两个关键字,分别是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
来自,导入关键字
该进口关键字用于某些模块导入到当前的命名空间。在从......进口用于从一个模块中导入一些特殊的属性。
范例程式码
现场演示
#Keywords from, import from math import factorial print(factorial(12))
输出结果
479001600
全局关键字
全球关键字被用于表示一个变量,它是一个块内使用的全局变量。如果不存在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关键字
该拉姆达关键字用来做一些匿名函数。对于匿名函数,没有名称。它就像一个内联函数。匿名函数中没有return语句。
范例程式码
现场演示
#Keyword lambda square = lambda x: x**2 for item in range(5, 10): print(square(item))
输出结果
25 36 49 64 81
非本地关键字
在外地关键字用来做声明的嵌套函数的变量是不是本地的。因此它是外部函数的局部变量,而不是内部函数的局部变量。此关键字用于修改某些非局部变量值,否则处于只读模式。
范例程式码
#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
通过关键字
该通关键字基本上是在Python的空语句。当通执行,没有任何反应。此关键字用作占位符。
范例程式码
#Keyword pass defsample_function(): pass #Not implemented now sample_function()
输出结果
(No Output will come)
while,break,continue和关键字
的同时,在Pythonwhile循环。该休息语句用来从电流回路,并且控制转移到款,这是紧接在循环之下出来。将继续用于忽略当前迭代。它以不同的循环移至下一个迭代。
的和关键字在Python用于逻辑和操作中,当两个操作数都为真,则返回真值。
范例程式码
#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
与,作为关键字
在与语句用于包装一个代码集的执行中,一种方法,它是由上下文管理器定义内。的作为关键字用于创建别名。
范例程式码
#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
~!@#$%^&*()_+/*-+\][{}|:;"'<.>/,'"]收益关键字
该产量关键字用来返回一个发电机。生成器是迭代器。它一次生成一个元素。
范例程式码
#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关键字执行逻辑或运算。当至少一个操作数为true时,答案将为true。
范例程式码
#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语句。条件为true时,不返回任何内容,但条件为false时,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:无关键字
该无是Python中的特殊常量。表示空值或不存在值。我们不能创建多个none对象,但是可以将其分配给不同的变量。
范例程式码
#Keyword None
deftest_function(): #This function will return None
print('Hello')
x = test_function()
print(x)输出结果
Hello None