Python关键字

Python关键字: 介绍

null

Python中的关键字 是不能用作变量名、函数名或任何其他标识符的保留字。

Python中所有关键字的列表

明确肯定 打破
持续 def 德尔
否则如果 其他的 除了 错误的
最后 对于 从…起 全球的
如果 进口 在里面
拉姆达 没有一个 非本地
通过 提升 回来
符合事实的 尝试 虽然 具有
产量

我们还可以使用下面的代码获取所有关键字名称。

示例: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)


输出:

关键词列表如下:

[‘False’,’None’,’True’,’and’,’as’,’assert’,’async’,’await’,’break’,’class’,’continue’,’def’,’del’,’elif’,’else’,’Exception’,’finally’,’for’,’from’,’global’,’if’,’import’,’in’,’is lambda’,’nonlocal’,’not or’,’pass’,’raise return’,“while”、“with”、“yield”]

让我们借助好的例子详细讨论每个关键字。

对,错,没有

  • 没错: 此关键字用于表示布尔值true。如果一条陈述是真的,则打印“真”。
  • 错: 此关键字用于表示布尔值false。如果一个陈述是虚假的,则打印“虚假”。
  • 无: 这是一个特殊常数,用于表示空值或空值。重要的是要记住,0,任何空容器(例如空列表)都不会计算为无。 它是其数据类型的对象–非类型。不可能创建多个无对象,并且可以将它们分配给变量。

示例: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

而且,或者,不是,在,是

  • :这是python中的逻辑运算符。“和” 返回第一个假值。如果找不到,请最后返回 “和”的真值表如下所示。

and keyword python

3和0 返回0

3和10 返回10

10或20或30或10或70次退货 10

对于一个来自这样一种语言的程序员来说,上面的语句可能有点让人困惑 C 其中逻辑运算符始终返回布尔值(0或1)。以下几行是直接从 python文档 解释如下:

表达式x和y首先计算x;如果x为false,则返回其值;否则,计算y并返回结果值。

表达式x或y首先计算x;如果x为真,则返回其值;否则,计算y并返回结果值。

笔记 既不限制返回的值和类型为False和True,也不限制返回的值和类型,而是返回最后计算的参数。这有时很有用,例如,如果s是一个字符串,如果它是空的,则应该用默认值替换,则表达式s或“foo”会生成所需的值。因为not必须创建一个新值,所以无论参数的类型如何,它都会返回一个布尔值(例如,not’foo’生成False而不是“.”)

  • :这是python中的逻辑运算符。或“返回第一个真值”。如果没有找到,最后返回。“或”的真值表如下所示。

or

3或0 返回3

3或10 返回3

0或0或3或10或0返回 3.

  • 不是: 此逻辑运算符反转真值。“非”的真值表如下所示。
  • 在: 此关键字用于检查容器是否包含值。该关键字还用于循环容器。
  • 是: 该关键字用于测试对象标识,即检查两个对象是否具有相同的内存位置。

示例:and、or、not、is和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 ( "
"
)
# 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”的功能,用于控制流量和循环。
  • 打破 : “中断”用于控制回路的流量。该语句用于跳出循环,并将控制传递给循环后紧跟的语句。
  • 持续 : “continue”还用于控制代码流。关键字跳过循环的当前迭代,但不结束循环。

例如: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

  • 如果 :这是一种决策控制声明。 真理表达式迫使控制进入“如果”语句块。
  • 其他的 :这是一种决策控制声明。 错误表达式强制控件进入“else”语句块。
  • 否则如果 :这是一种决策控制声明。它是“的缩写” 否则如果

示例: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

注: 有关更多信息,请参阅out Python if-else教程 .

def

def关键字用于声明用户定义的函数。

示例:def关键字

Python3

# def keyword
def fun():
print ( "Inside Function" )
fun()


输出

Inside Function

退货关键字–退货,收益率

  • 返回: 此关键字用于从函数返回。
  • 收益率: 该关键字与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类和对象教程 .

具有

具有 关键字用于在上下文管理器定义的方法中包装代码块的执行。这个关键字在日常编程中使用不多。

示例:使用关键字

Python3

# using with statement
with open ( 'file_path' , 'w' ) as file :
file .write( 'hello world !' )


关键字用于为导入的模块创建别名。i、 e为导入的模块赋予新名称。将数学作为mymath导入。

例如:as关键字

Python3

import math as gfg
print (gfg.factorial( 5 ))


输出

120

通过

通过 是python中的null语句。遇到这种情况时不会发生任何事情。这用于防止缩进错误,并用作占位符。

示例:Pass关键字

Python3

n = 10
for i in range (n):
# pass can be used as placeholder
# when code is to added later
pass


拉姆达

拉姆达 关键字用于生成内部不允许使用语句的内联返回函数。

示例:Lambda关键字

Python3

# Lambda keyword
g = lambda x: x * x * x
print (g( 7 ))


输出

343

从…进口

  • 进口 : 此语句用于将特定模块包含到当前程序中。
  • 发件人: 通常与导入一起使用,“从”用于从导入的模块导入特定功能。

示例:导入,来自关键字

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

  • 尝试: 此关键字用于异常处理,用于使用关键字except捕获代码中的错误。如果存在任何类型的错误,则检查“try”块中的代码,但执行块除外。
  • 除了: 如上所述,这与“尝试”捕获异常一起工作。
  • 最后: 无论“try”块的结果是什么,总是执行名为“finally”的块。
  • 提出: 我们可以使用raise关键字显式地引发异常
  • 断言: 此函数用于 调试目的 .通常用于检查代码的正确性。如果一个陈述被评估为真,什么也不会发生,但当它是假的时候,” 断言错误 “是的。你也可以 打印带有错误的消息,以逗号分隔 .

示例: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关键字

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

全局的,非局部的

  • 全球的: 此关键字用于定义函数中的全局变量。
  • 非本地: 该关键字的工作原理与全局关键字类似,但与全局关键字不同,该关键字声明了一个变量,以在嵌套函数的情况下指向外部封闭函数的变量。

示例:全局和非局部关键字

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中的全局和局部变量教程 .

本文由 曼吉特·辛格(S.南迪尼) .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞15 分享