大数跨境
0
0

Python中常见关键字解释

Python中常见关键字解释 AI算法之道
2024-05-23
0
导读:理解Python中关键字用法











01


引言



本文重点介绍了Python中的各个关键字及其用途,包括函数定义、返回值、生成器、匿名函数、类型判断、逻辑运算、条件语句、循环、异常处理、类定义、异步编程以及全局和非局部变量的声明。


闲话少说,我们直接开始吧!






02


 def


关键字def允许我们编写自己的函数--函数是小代码块,可以随意重复使用。
# defining a function hellodef hello():  print('hello')

# calling (using) the function hellohello()




03


  return


关键字return表示函数的输出。样例如下:

def add10(n):  return n + 10
x = add10(4)print(x)
# 14

上述代码中,n+10 位于return关键字的右侧,因此 n+10 是函数的输出。注意,函数中的return语句运行后不会再运行任何其他内容。





04


  yield

关键字yield也常常用于表示函数的输出。但与 return 语句不同的是,在 yield 运行后,任务仍然可以运行,这也意味着我们的函数可以有多个输出结果

def test():  yield 1  yield 2  yield 3  yield 4
for n in test(): print(n)

运行上述代码后,输出如下:

# 1# 2# 3# 4

在函数中使用 yield 使其成为生成器函数,这意味着它有多个输出,我们需要使用 for 循环来调用它。







05


 lambda


关键字lambda 允许我们编写小型匿名函数。

def add100(n):  return n + 100

上面的例子是一个使用 def 定义的普通函数。

# lambda function_inputs: function_output
add100 = lambda n: n+100

上面的例子是使用 lambda 定义的功能完全相同的函数。

lambda n: n+100

上面的例子中,lambda 函数是匿名的,因为给它取名是可选的。在这里,我们去掉了它的名字,它就变成了匿名函数。





06


 None


关键字None 表示 None 类型,它用以表示Nothing

def hello():  print('hello')
x = hello() # hello
print(x) # None

如果我们在函数中不返回任何内容,它默认返回 None






07


with

关键字with允许我们使用上下文管理器。

with open('a.txt') as f:  # do stuff with f

上述代码中,open('a.txt') 就是相关的上下文管理器。它包含两个特殊方法 __enter__ __exit__,分别在 with 代码块的开始和结束时运行。

在这种情况下,当 with 代码块结束后,__exit__ 将运行以正确关闭文件 a.txt,从而防止内存泄漏和其他不好的事情发生。




08


as

关键字as允许我们使用别名。

with open('a.txt') as f:  # do stuff

在上述代码中,open('a.txt')返回的对象被赋予了别名 f,这样我们就可以方便地引用它。

import numpy as np

上述代码中,我们导入了numpy库,但给它起了一个别名 np--这意味着从现在起,当我们要引用 numpy 时,只需使用 np 即可。





09


import

关键字import 允许我们在代码中导入其他 Python 库和模块。

import numpy as npimport pandas as pdimport requests

这非常有用,因为有很多 Python 库能让我们做很多很酷的事情。





10


from

使用 from 关键字,我们可以导入模块的特定部分,而不是整个模块。

from numpy import array

在这里,我们不导入整个 numpy,而只导入了array模块。

from requests import get, post

在这里,我们只从request中导入getpost函数。




11


del

使用del关键字,我们可以删除代码中的内容。

a = 4b = 5
del b
print(a) # 4print(b) # ERROR

在上述代码中,我们删除了变量 b,因此当我们尝试打印 b 时会出现错误

d = {'apple':4, 'orange':5, 'pear':6}del d['apple']
print(d)
# {'orange':5, 'pear':6}

在这里,我们删除了 d['apple'],因此'apple':4 键值对被删除。





12


True & False

关键字True False 是布尔类型中仅有的两个值,我们在条件语句中使用它们。

if True:  print('this will run')
if False: print('this will never run')




13


and & or & not

关键字and or 以及 not 逻辑运算符,可用于包含多个条件的条件语句中。

x = 5if x > 3 and x < 7:  print('x is more than 3 and less than 7')

上述代码中,and运算符中的两个条件都必须为True时,该表达式才为真。

x = 5if x > 3 or x < 7:  print('either one condition needs to be True for this to print')

上述代码中,or运算符中至少有一个条件为真时,整个表达式才为真。

print(not True)    # Falseprint(not False)   # True

运算符not 简单的切换逻辑变量TrueFalse





14


if elif & else

关键字if elif 和 else 均用于编写条件语句。

score = 57
if score >= 90: print('grade A')
elif score >= 80: print('grade B')
elif score >= 70: print('grade C')
else: print('fail')

上述代码中,可以有多个elif表示多个可选条件,但是最多只能有一个else语句,表示其他条件不满足时的处理逻辑。






15


 type

通过 type 关键字,我们可以获取变量的数据类型

a = 1print(type(a))   # <class 'int'>
b = 'apple'print(type(b)) # <class 'str'>






16


 class

关键字class用于创建类,然后对类进行初始化以创建对象。

class Dog:  pass
dog = Dog()

上述代码中,Dog 是一个类,而 dog 表示一个对象。






17


 for

关键字 for 用于编写循环语句,该循环用于重复有限次数的操作。

for i in range(5):  print('hello')

在这里,我们使用 for 循环重复 print('hello') 5 次。






18


 while

关键字 while 用于编写 while 循环,该循环用于无限重复操作,直到满足特定条件。

n = 1
while n < 3: print(n) n += 1
# 1# 2# 3






19


 pass

关键字 pass 表示什么也不做。我们通常将其用作尚未决定如何编写代码的占位符。

def hello():  pass





20


 break

for 循环或 while 循环中使用 break 关键字时,会立即停止循环。

for i in range(1, 11):  print(i)
if i == 3: break
# 1# 2# 3

在这里,我们在 i == 3 时中断,这就是为什么我们的整个 for 循环会在此时停止,之后不会再发生任何事情。







21


 continue

for 循环或 while 循环中使用 continue 关键字时,会立即停止当前迭代,并跳转到下一次迭代。这并不会停止整个循环。

for i in range(1, 6):  if i == 3:    continue
print(i)
# 1# 2# 4# 5

在这里,当 i == 3 时,我们继续并直接跳到下一次迭代,但不会像 break 那样停止整个循环。







22


 try & except

关键字try用于尝试可能导致错误的代码,而except关键字用于定义如何处理 try 代码块产生的任何错误。

try:  x = 1 + 'apple'except:  print('error!!')
# error!!

在这里,我们试图将一个整数与一个字符串相加,这会导致错误,从而运行 except 代码块。







23


finally

关键字finally 代码块用于 try except 之后,无论 try 代码块中是否发生错误,finally 代码块中的内容都将始终运行。

try:  x = 1 + 'apple'except:  print('error!!')finally:  print('this will always run')
# error!!# this will always run

我们通常使用 finally 来运行必须运行的清理代码,例如关闭文件。







24


assert

我们使用断言assert作为正确性检查。如果我们断言条件,而条件评估为 True,则不会发生任何事情。但如果条件评估为 False,我们就会得到一个 AssertionError

x = 1assert type(x) == int
# nothing happens
x = 'apple'assert type(x) == int
# AssertionError






25


raise

我们使用 raise 来强制导致异常或错误发生。

x = 1
if type(x) != int: raise Exception('x must be an integer!!')
# nothing happens
x = 1
if type(x) != int: raise Exception('x must be an integer!!')
# Exception: x must be an integer!!






26


match & case

关键字match case 可用作 if-else 块的替代。

fruit = 'appple'
match fruit: case 'apple': print('apple juice') case 'orange': print('orange pie') case 'pear': print('pear cake')
# apple juice

在这里,由于 fruit == 'apple'情况发生,我们打印 apple juice.







27


in

关键字 in 用于检查某元素是否在其集合的内部。

fruits = ['apple', 'orange', 'pear']
print('apple' in fruits) # Trueprint('pineapple' in fruits) # False






28


is

关键字 is 用于检查两个变量是否指向同一对象

a = ['apple', 'orange']b = a
print(a is b) # True
a = ['apple', 'orange']b = ['apple', 'orange']
print(a is b) # False







29


async wait

关键字async await 关键字用于编写异步 Python 函数,我们可以并发运行而不是按顺序运行。

async def my_coroutine():    print('coroutine started')    await asyncio.sleep(1)    print("coroutine ended")







30


global

关键字global 用于定义变量为全局变量。

x = 5
def test(): x = 100
test()print(x) # 5

上述代码中中,函数test() 运行时,x = 100 运行,但在测试函数中,x 位于局部域,因此不会覆盖全局 x。

x = 5
def test(): global x x = 100
test()print(x) # 100

在上述代码中,global x 使 x 指向全局 ,这就是为什么设置 x = 100 也会影响全局 x 的原因。







31


nonlocal

关键字nonlocal的行为与全局关键字类似,但它适用于嵌套函数内部的变量。

def test():  x = 5    def test2():    nonlocal x    x = 100
test2() print(x)
test()
# 100







32


结论

本文重点介绍了Python语言中的关键字,使得编程更加直观和简洁。通过合理使用Python的关键字,可以编写出既高效又易于维护的代码,此外,理解这些关键字对于成为一个熟练的Python程序员至关重要。








点击上方小卡片关注我




扫码进群,交个朋友!


【声明】内容源于网络
0
0
AI算法之道
一个专注于深度学习、计算机视觉和自动驾驶感知算法的公众号,涵盖视觉CV、神经网络、模式识别等方面,包括相应的硬件和软件配置,以及开源项目等。
内容 573
粉丝 0
AI算法之道 一个专注于深度学习、计算机视觉和自动驾驶感知算法的公众号,涵盖视觉CV、神经网络、模式识别等方面,包括相应的硬件和软件配置,以及开源项目等。
总阅读23
粉丝0
内容573