python中的保留字介绍

  • 1. False:
  • 2. None:
  • 3. True:
  • 4. and:
  • 5. as:
  • 6. assert:
  • 7. async:
  • 8. await:
  • 9. break:
  • 10. class:
  • 11. continue:
  • 12. def:
  • 13. del:
  • 14. elif:
  • 15. else:
  • 16. except:
  • 17. finally:
  • 18. for:
  • 19. from:
  • 20. global:
  • 21. if:
  • 22. import:
  • 23. in:
  • 24. is:
  • 25. lambda:
  • 26. nonlocal:
  • 27. not:
  • 28. or:
  • 29. pass:
  • 30. raise:
  • 31. return:
  • 32. try:
  • 33. while:
  • 34. with:
  • 35. yield:
  • 在Python中,保留字(也称为关键字)是具有特殊含义的单词,不能用作标识符(如变量名、函数名等)。Python最新版本中有 35 个保留字

    1. False:

  • 布尔类型的假值
  • if not True:
        print(False)
    

    2. None:

  • 表示空值或不存在的对象
  • value = None
    if value is None:
        print("Value is None")
    

    3. True:

  • 布尔类型的真值
  • if True:
        print("This will always print")
    

    4. and:

  • 逻辑与运算符
  • if True and False:
        print("This won't print")
    

    5. as:

  • 用于模块导入时的别名设定,或者在上下文管理器中使用
  • import numpy as np
    a = np.array([1, 2, 3])
    

    6. assert:

  • 用于调试时的断言,检查表达式是否为真,否则引发 AssertionError
  • assert 2 + 2 == 4, "Math is broken!"
    

    7. async:

  • 用于定义异步函数或与异步操作相关
  • async def my_coroutine():
        print("Coroutine is running")
    

    8. await:

  • 用于等待异步函数的完成
  • async def main():
        await my_coroutine()
    

    9. break:

  • 用于终止循环
  • for i in range(5):
        if i == 3:
            break
        print(i)
    

    10. class:

  • 用于定义类
  • class MyClass:
        def __init__(self):
            self.value = 0
    

    11. continue:

  • 用于跳过当前循环的剩余语句,继续下一次循环
  • for i in range(5):
        if i == 2:
            continue
        print(i)
    

    12. def:

  • 用于定义函数
  • def my_function():
        print("Hello, world!")
    

    13. del:

  • 用于删除对象或对象的属性
  • my_list = [1, 2, 3]
    del my_list[1]
    print(my_list)  # Output: [1, 3]
    

    14. elif:

  • else if 的缩写,用于条件判断
  • x = 10
    if x > 20:
        print("x is greater than 20")
    elif x > 10:
        print("x is between 10 and 20")
    else:
        print("x is 10 or less")
    

    15. else:

  • 用于条件判断或循环的 else 部分
  • x = 5
    if x > 10:
        print("x is greater than 10")
    else:
        print("x is 10 or less")
    

    16. except:

  • 用于异常处理,捕获特定异常
  • try:
        x = 1 / 0
    except ZeroDivisionError:
        print("Cannot divide by zero")
    

    17. finally:

  • 用于异常处理,无论是否发生异常都会执行
  • try:
        x = 1 / 0
    except ZeroDivisionError:
        print("Cannot divide by zero")
    finally:
        print("This will always execute")
    

    18. for:

  • 用于循环迭代
  • for i in range(5):
        print(i)
    

    19. from:

  • 用于模块导入,指定从哪个模块导入
  • from math import sqrt
    print(sqrt(16))  # Output: 4.0
    

    20. global:

  • 用于声明变量是在全局作用域中
  • x = 0
    def func():
        global x
        x = 1
    func()
    print(x)  # Output: 1
    

    21. if:

  • 用于条件判断
  • if x > 0:
        print("x is positive")
    

    22. import:

  • 用于导入模块
  • import math
    print(math.pi)
    

    23. in:

  • 用于成员资格测试或迭代中的循环
  • if 2 in [1, 2, 3]:
        print("2 is in the list")
    

    24. is:

  • 用于身份测试,检查两个对象是否是同一个实例
  • a = [1, 2, 3]
    b = a
    print(a is b)  # Output: True
    

    25. lambda:

  • 用于创建匿名函数
  • double = lambda x: x * 2
    print(double(5))  # Output: 10
    

    26. nonlocal:

  • 用于声明变量是在闭包的外部作用域中,但不是全局的
  • def outer():
        x = 1
        def inner():
            nonlocal x
            x = 2
        inner()
        print(x)  # Output: 2
    outer()
    

    27. not:

  • 逻辑非运算符
  • if not True:
        print("This won't print")
    

    28. or:

  • 逻辑或运算符
  • if True or False:
        print("This will print")
    

    29. pass:

  • 空语句,用于占位
  • def my_function():
        pass  # To be implemented later
    

    30. raise:

  • 用于引发异常。
  • raise ValueError("Invalid value")
    

    31. return:

  • 用于从函数中返回值
  • def add(a, b):
        return a + b
    print(add(1, 2))  # Output: 3
    

    32. try:

  • 用于异常处理,尝试执行可能抛出异常的代码
  • try:
        x = 1 / 0
    except ZeroDivisionError:
        print("Cannot divide by zero")
    

    33. while:

  • 用于循环,当条件为真时重复执行代码块
  • i = 0
    while i < 5:
        print(i)
        i += 1
    

    34. with:

  • 用于上下文管理器,确保资源正确管理
  • with open('file.txt', 'r') as f:
        content = f.read()
    

    35. yield:

  • 用于生成器函数,暂停函数并返回值,保持状态以便后续调用
  • def my_generator():
        yield 1
        yield 2
        yield 3
    gen = my_generator()
    for value in gen:
        print(value)
    

    作者:Colin♛

    物联沃分享整理
    物联沃-IOTWORD物联网 » python中的保留字介绍

    发表回复