Python关键字
Python关键字:简介
Python中的关键字是不能用作变量名、函数名或任何其他标识符的保留字。
Python中所有关键字的列表
and | as | assert | break |
class | continue | def | del |
elif | else | except | False |
finally | for | from | global |
if | import | in | is |
lambda | None | nonlocal | not |
or | pass | raise | return |
True | try | while | with |
yield |
我们还可以使用以下代码获取所有关键字名称。
示例: Python关键字列表
Python3
# Python code to demonstrate working of iskeyword()
# importing "keyword" for keyword operations
import keyword
# printing all keywords at once using "kwlist()"
print("The list of keywords is : ")
print(keyword.kwlist)
Python3
print(False == 0)
print(True == 1)
print(True + True + True)
print(True + False + False)
print(None == 0)
print(None == [])
Python
# showing logical operation
# or (returns True)
print(True or False)
# showing logical operation
# and (returns False)
print(False and True)
# showing logical operation
# not (returns False)
print(not True)
# using "in" to check
if 's' in 'geeksforgeeks':
print("s is part of geeksforgeeks")
else:
print("s is not part of geeksforgeeks")
# using "in" to loop through
for i in 'geeksforgeeks':
print(i, end=" ")
print("\r")
# using is to check object identity
# string is immutable( cannot be changed once allocated)
# hence occupy same memory location
print(' ' is ' ')
# using is to check object identity
# dictionary is mutable( can be changed once allocated)
# hence occupy different memory location
print({} is {})
Python3
# Using for loop
for i in range(10):
print(i, end = " ")
# break the loop as soon it sees 6
if i == 6:
break
print()
# loop from 1 to 10
i = 0
while i <10:
# If i is equals to 6,
# continue to next iteration
# without printing
if i == 6:
i+= 1
continue
else:
# otherwise print the value
# of i
print(i, end = " ")
i += 1
Python3
# Python program to illustrate if-elif-else ladder
#!/usr/bin/python
i = 20
if (i == 10):
print ("i is 10")
elif (i == 20):
print ("i is 20")
else:
print ("i is not present")
Python3
# def keyword
def fun():
print("Inside Function")
fun()
Python3
# Return keyword
def fun():
S = 0
for i in range(10):
S += i
return S
print(fun())
# Yield Keyword
def fun():
S = 0
for i in range(10):
S += i
yield S
for i in fun():
print(i)
Python3
# Python3 program to
# demonstrate instantiating
# a class
class Dog:
# A simple class
# attribute
attr1 = "mammal"
attr2 = "dog"
# A sample method
def fun(self):
print("I'm a", self.attr1)
print("I'm a", self.attr2)
# Driver code
# Object instantiation
Rodger = Dog()
# Accessing class attributes
# and method through objects
print(Rodger.attr1)
Rodger.fun()
Python3
# using with statement
with open('file_path', 'w') as file:
file.write('hello world !')
Python3
import math as gfg
print(gfg.factorial(5))
Python3
n = 10
for i in range(n):
# pass can be used as placeholder
# when code is to added later
pass
Python3
# Lambda keyword
g = lambda x: x*x*x
print(g(7))
Python3
# import keyword
import math
print(math.factorial(10))
# from keyword
from math import factorial
print(factorial(10))
Python3
# initializing number
a = 4
b = 0
# No exception Exception raised in try block
try:
k = a//b # raises divide by zero exception.
print(k)
# handles zerodivision exception
except ZeroDivisionError:
print("Can't divide by zero")
finally:
# this block is always executed
# regardless of exception generation.
print('This is always executed')
# assert Keyword
# using assert to check for 0
print ("The value of a / b is : ")
assert b != 0, "Divide by 0 error"
print (a / b)
Python3
my_variable1 = 20
my_variable2 = "GeeksForGeeks"
# check if my_variable1 and my_variable2 exists
print(my_variable1)
print(my_variable2)
# delete both the variables
del my_variable1
del my_variable2
# check if my_variable1 and my_variable2 exists
print(my_variable1)
print(my_variable2)
Python3
# global variable
a = 15
b = 10
# function to perform addition
def add():
c = a + b
print(c)
# calling a function
add()
# nonlocal keyword
def fun():
var1 = 10
def gun():
# tell python explicitly that it
# has to access var1 initialized
# in fun on line 2
# using the keyword nonlocal
nonlocal var1
var1 = var1 + 10
print(var1)
gun()
fun()
输出:
The list of keywords is :
[‘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’]
让我们借助好的示例详细讨论每个关键字。
真,假,无
- True:此关键字用于表示布尔值 true。如果语句为真,则打印“True”。
- False:此关键字用于表示布尔值 false。如果语句为假,则打印“False”。
- 无:这是一个特殊的常量,用于表示空值或空值。重要的是要记住,0,任何空容器(例如空列表)都不会计算为无。
它是其数据类型的对象——NoneType。无法创建多个 None 对象并将它们分配给变量。
示例:True、False 和 None 关键字
Python3
print(False == 0)
print(True == 1)
print(True + True + True)
print(True + False + False)
print(None == 0)
print(None == [])
True
True
3
1
False
False
and, or, not, in, is
- and :这是Python中的逻辑运算符。 “and”返回第一个假值。如果没有找到最后返回。 “和”的真值表如下所示。
3 和 0返回 0
3 和 10返回 10
10 或 20 或 30 或 10 或 70 返回10
对于来自像C语言这样的逻辑运算符总是返回布尔值(0 或 1)的程序员来说,上述语句可能有点令人困惑。以下几行直接来自解释这一点的Python文档:
The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.
The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.
请注意,and 或 or 都不会限制它们返回的值和类型为 False 和 True,而是返回最后评估的参数。这有时很有用,例如,如果 s 是一个字符串,如果它是空的,则应该将其替换为默认值,则表达式 s 或 'foo' 会产生所需的值。因为 not 必须创建一个新值,所以无论其参数的类型如何,它都会返回一个布尔值(例如,not 'foo' 产生 False 而不是 '.)
- or :这是Python中的逻辑运算符。 “或” 返回第一个 True 值。如果没有找到返回最后一个。 “或”的真值表如下所示。
3 或 0返回 3
3 或 10返回 3
0 或 0 或 3 或 10 或 0 返回3
- not:此逻辑运算符反转真值。 “非”的真值表如下所示。
- in:该关键字用于检查容器是否包含值。该关键字也用于循环容器。
- is:此关键字用于测试对象身份,即检查两个对象是否占用相同的内存位置。
示例:and, or, not, is and in 关键字
Python
# showing logical operation
# or (returns True)
print(True or False)
# showing logical operation
# and (returns False)
print(False and True)
# showing logical operation
# not (returns False)
print(not True)
# using "in" to check
if 's' in 'geeksforgeeks':
print("s is part of geeksforgeeks")
else:
print("s is not part of geeksforgeeks")
# using "in" to loop through
for i in 'geeksforgeeks':
print(i, end=" ")
print("\r")
# using is to check object identity
# string is immutable( cannot be changed once allocated)
# hence occupy same memory location
print(' ' is ' ')
# using is to check object identity
# dictionary is mutable( can be changed once allocated)
# hence occupy different memory location
print({} is {})
输出:
True
False
False
s is part of geeksforgeeks
g e e k s f o r g e e k s
True
False
迭代关键字——for、while、break、continue
- for :此关键字用于控制流程和 for 循环。
- while :具有类似“for”的工作原理,用于控制流程和 for 循环。
- break : “break”用于控制循环的流程。该语句用于跳出循环并将控制权传递给紧接在循环之后的语句。
- continue : “continue”也用于控制代码的流动。关键字跳过循环的当前迭代,但不结束循环。
示例:for、while、break、continue 关键字
Python3
# Using for loop
for i in range(10):
print(i, end = " ")
# break the loop as soon it sees 6
if i == 6:
break
print()
# loop from 1 to 10
i = 0
while i <10:
# If i is equals to 6,
# continue to next iteration
# without printing
if i == 6:
i+= 1
continue
else:
# otherwise print the value
# of i
print(i, end = " ")
i += 1
0 1 2 3 4 5 6
0 1 2 3 4 5 7 8 9
条件关键字——if、else、elif
- if :它是用于决策的控制语句。真值表达强制控制进入“if”语句块。
- else :它是用于决策的控制语句。错误表达式强制控制进入“else”语句块。
- elif :它是用于决策的控制语句。它是“ else if ”的缩写
示例:if、else 和 elif 关键字
Python3
# Python program to illustrate if-elif-else ladder
#!/usr/bin/python
i = 20
if (i == 10):
print ("i is 10")
elif (i == 20):
print ("i is 20")
else:
print ("i is not present")
i is 20
注意:有关更多信息,请参阅Python if else 教程。
定义
def 关键字用于声明用户定义的函数。
示例:def 关键字
Python3
# def keyword
def fun():
print("Inside Function")
fun()
Inside Function
退货关键词——退货、收益
- return:此关键字用于从函数返回。
- yield :此关键字与 return 语句类似,但用于返回生成器。
示例:Return 和 Yield 关键字
Python3
# Return keyword
def fun():
S = 0
for i in range(10):
S += i
return S
print(fun())
# Yield Keyword
def fun():
S = 0
for i in range(10):
S += i
yield S
for i in fun():
print(i)
45
0
1
3
6
10
15
21
28
36
45
班级
class关键字用于声明用户定义的类。
示例:类关键字
Python3
# Python3 program to
# demonstrate instantiating
# a class
class Dog:
# A simple class
# attribute
attr1 = "mammal"
attr2 = "dog"
# A sample method
def fun(self):
print("I'm a", self.attr1)
print("I'm a", self.attr2)
# Driver code
# Object instantiation
Rodger = Dog()
# Accessing class attributes
# and method through objects
print(Rodger.attr1)
Rodger.fun()
mammal
I'm a mammal
I'm a dog
注意:有关更多信息,请参阅我们的Python类和对象教程。
和
with关键字用于将代码块的执行包装在上下文管理器定义的方法中。这个关键字在日常编程中使用不多。
示例:使用关键字
Python3
# using with statement
with open('file_path', 'w') as file:
file.write('hello world !')
作为
as关键字用于为导入的模块创建别名。即给导入的模块一个新名称。例如,将数学导入为 mymath。
示例:作为关键字
Python3
import math as gfg
print(gfg.factorial(5))
120
经过
经过 是Python中的空语句。遇到这种情况时没有任何反应。这用于防止缩进错误并用作占位符。
示例:密码关键字
Python3
n = 10
for i in range(n):
# pass can be used as placeholder
# when code is to added later
pass
拉姆达
Lambda关键字用于制作内联返回函数,内部不允许使用任何语句。
示例:Lambda 关键字
Python3
# Lambda keyword
g = lambda x: x*x*x
print(g(7))
343
进口于
- import :此语句用于将特定模块包含到当前程序中。
- from :通常与 import 一起使用,from 用于从导入的模块中导入特定的功能。
示例:导入,来自关键字
Python3
# import keyword
import math
print(math.factorial(10))
# from keyword
from math import factorial
print(factorial(10))
3628800
3628800
异常处理关键字——try、except、raise、finally 和 assert
- try :该关键字用于异常处理,用于捕捉代码中的错误,使用关键字except。检查“try”块中的代码,如果有任何类型的错误,除了块被执行。
- except :如上所述,这与“try”一起使用以捕获异常。
- finally :无论“try”块的结果是什么,称为“finally”的块总是被执行。
- raise:我们可以使用 raise 关键字显式地引发异常
- assert:此函数用于调试目的。通常用于检查代码的正确性。如果一个语句被评估为真,则什么也不会发生,但是当它为假时,会引发“ AssertionError ”。也可以打印带有错误的消息,用逗号分隔。
示例:try、except、raise、finally 和 assert 关键字
Python3
# initializing number
a = 4
b = 0
# No exception Exception raised in try block
try:
k = a//b # raises divide by zero exception.
print(k)
# handles zerodivision exception
except ZeroDivisionError:
print("Can't divide by zero")
finally:
# this block is always executed
# regardless of exception generation.
print('This is always executed')
# assert Keyword
# using assert to check for 0
print ("The value of a / b is : ")
assert b != 0, "Divide by 0 error"
print (a / b)
输出
Can't divide by zero
This is always executed
The value of a / b is :
AssertionError: Divide by 0 error
注意:有关更多信息,请参阅我们的教程Python中的异常处理教程。
德尔
del用于删除对对象的引用。可以使用 del 删除任何变量或列表值。
示例:del 关键字
Python3
my_variable1 = 20
my_variable2 = "GeeksForGeeks"
# check if my_variable1 and my_variable2 exists
print(my_variable1)
print(my_variable2)
# delete both the variables
del my_variable1
del my_variable2
# check if my_variable1 and my_variable2 exists
print(my_variable1)
print(my_variable2)
输出
20
GeeksForGeeks
NameError: name 'my_variable1' is not defined
全球,非本地
- global:此关键字用于将函数内部的变量定义为全局范围。
- non-local :此关键字的工作方式类似于 global,但不是 global,此关键字声明一个变量以指向外部封闭函数的变量,以防嵌套函数。
示例:全局和非本地关键字
Python3
# global variable
a = 15
b = 10
# function to perform addition
def add():
c = a + b
print(c)
# calling a function
add()
# nonlocal keyword
def fun():
var1 = 10
def gun():
# tell python explicitly that it
# has to access var1 initialized
# in fun on line 2
# using the keyword nonlocal
nonlocal var1
var1 = var1 + 10
print(var1)
gun()
fun()
25
20
注:对于 更多信息,请参阅我们的Python中的全局和局部变量教程。