python学习笔记-关键字

Python中的关键字是一组被编程语言保留用于特定目的的单词。这些关键字具有特殊含义,不能被用作变量名或标识符。下面是python中的关键字:

False      await      else       import     pass
None       break      except     in         raise
True       class      finally    is         return
and        continue   for        lambda     try
as         def        from       nonlocal   while
assert     del        global     not        with
async      elif       if         or         yield

另外我们还可以通过 keyword模块获取关键字信息,通过help函数获取帮助信息:

import keyword
for kw in keyword.kwlist:
    print(kw,end=" ")
print()
print('='*50)
help("yield")

控制台输出:
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 
==================================================
The "yield" statement
*********************

   yield_stmt ::= yield_expression

A "yield" statement is semantically equivalent to a yield expression.
The yield statement can be used to omit the parentheses that would
otherwise be required in the equivalent yield expression statement.
For example, the yield statements

False

表示布尔类型的假值。

True

表示布尔类型的真值。

None

表示一个空值或者什么都没有。

x = None
if x is None:
    print("x is None ")
    print(type(x))
else:
    print("x is not None")

==================================================
x is None
<class 'NoneType'>

and

逻辑与操作符。

x = True
y = False
z = x and y
print(z)  # 输出 False

or

逻辑或操作符。

x = True
y = False
z = x or y
print(z)  # 输出 True

not

逻辑非操作符。

x = True
y = not x
print(y)  # 输出 False

if

条件语句,用于根据条件执行不同的代码块。

elif

条件语句中的"else if",用于指定多个条件。

else

条件语句中的默认分支。

x = 10
if x > 5:
    print("x is greater than 5")
elif x < 5:
    print("x is less than 5")
else:
    print("x is equal to 5")

for

循环语句,用于迭代可迭代对象中的元素。

while

循环语句,用于在条件为真时重复执行代码块。

break

用于在循环中终止循环。

continue

用于跳过当前循环的剩余代码,继续下一次循环。

def

定义函数。

return

用于从函数中返回值。

def add(x, y):
    return x + y

result = add(3, 4)
print(result)  # 输出 7

class

定义类。

try

异常处理语句的开始部分。

except

异常处理语句的分支,用于捕获特定类型的异常。

finally

异常处理语句的分支,在无论是否发生异常时都会执行的代码块。

try:
    x = 10 / 0
except ZeroDivisionError:
    print("Error: division by zero")
finally:
    print("Finally block executed")

raise

用于引发异常。

x = -1
if x < 0:
    raise ValueError("x cannot be negative")

import

用于导入模块或者模块中的函数、类等。

from

从模块中导入特定的函数、类等。

as

用于给模块或者变量起别名。

from math import sqrt as sq
print(sq(16)) #输出4.0

lambda

创建匿名函数。

add = lambda x, y: x + y
print(add(3, 4))  # 输出 7

pass

占位符,不执行任何操作,用于保持代码结构完整性。

def my_function():
    pass

global

声明全局变量。

x = 10
def my_function():
    global x
    x = 20
my_function()
print(x)  # 输出 20

nonlocal

用于在嵌套函数中声明外部嵌套作用域中的变量。在嵌套函数中,通常可以访问外部函数的局部变量,但如果要在内部函数中修改外部函数的局部变量,就需要使用 nonlocal 关键字。

def outer_function():
    x = 10  # 外部函数的局部变量

    def inner_function():
        nonlocal x  # 声明要修改的外部函数的局部变量
        x = 20  # 修改外部函数的局部变量

    inner_function()
    print("Outer function's local variable x:", x)

outer_function()

输出20 没有nonlocal 输出10

async

声明异步函数。

  • async 关键字用于定义异步函数,标志着函数是一个协程(Coroutine),可以在其中使用 await 关键字来等待异步操作的完成。
  • 异步函数会立即返回一个协程对象,而不是实际执行函数体内的代码。

await

用于等待异步操作完成。

  • await 关键字用于暂停异步函数的执行,等待另一个异步操作的完成。它只能在异步函数内部使用。
  • 当遇到 await 关键字时,事件循环(Event Loop)会挂起当前协程的执行,执行其他协程或者异步操作,直到被等待的异步操作完成。
import asyncio

async def my_async_function():
    print("Start of async function")
    await asyncio.sleep(1)  # 等待1秒钟
    print("End of async function")

# 调用异步函数
asyncio.run(my_async_function())

 在异步编程中,asyncawait 关键字通常与 asyncio 模块一起使用,用于定义和执行异步操作,以实现并发执行和非阻塞 I/O。

with

创建上下文管理器,用于管理资源,确保在使用后正确地释放资源。

with open("example.txt", "r") as file:
        data = file.read()
        print(data)

assert:

用于在编写代码时进行断言测试。它用于在代码中设立断言(Assertion),如果断言为假,则会触发 AssertionError 异常。

x = 10
assert x == 10
print("Assertion passed")

assert x == 5,"x must be equal to 10" 
print("Assertion passed")

控制台输出
Assertion passed
Traceback (most recent call last):
  File "d:\python\test\test_bif.py", line 5, in <module>
    assert x == 5,"x must be equal to 10"
AssertionError: x must be equal to 10

del

  del 是用于删除对象的引用,可以删除变量、列表中的元素、字典中的键值对等。

in

  in 是用于检查某个值是否存在于序列(如列表、元组、字典等)中的关键字。

is

  is 是用于检查两个对象是否指向同一个内存地址的关键字。

x = [1, 2, 3]
y = [1, 2, 3]
z = x

print(x is y)  # 输出 False,因为 x 和 y 指向不同的内存地址
print(x is z)  # 输出 True,因为 x 和 z 指向同一个内存地址

yield :

用于定义生成器(Generator)。生成器是一种特殊的迭代器,可以在循环中逐个地产生值,而不需要一次性将所有值存储在内存中。

yield 关键字用于在生成器函数中生成值,并将生成的值返回给调用者。与 return 不同,yield 会暂停函数的执行,并保留函数的状态,以便在下一次调用时继续执行。

def my_generator():
    yield 1
    yield 2
    yield 3

gen = my_generator()

print(next(gen))  # 输出 1
print(next(gen))  # 输出 2
print(next(gen))  # 输出 3

 

  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值