欢迎访问宙启技术站
智能推送

最常用的Python关键字汇总

发布时间:2023-12-19 01:31:35

Python关键字是由Python语言定义的,具有特殊含义的保留字。下面是一些最常用的Python关键字的汇总:

1. and: 逻辑运算符,用于逻辑与操作。

例子:

if x > 0 and y > 0:
    print("Both x and y are positive")

2. as: 在import语句中使用,用于给导入的模块或包指定别名。

例子:

import math as m
print(m.sqrt(25))

3. assert: 用于测试一个条件是否为真,若为假则触发断言错误。

例子:

assert x > 0, "x must be positive"

4. break: 跳出当前循环体,停止执行后续的循环语句。

例子:

for num in range(10):
    if num == 5:
        break
    print(num)

5. class: 定义一个类。

例子:

class Dog:
    def __init__(self, name):
        self.name = name

    def bark(self):
        print("Woof!")

my_dog = Dog("Buddy")
print(my_dog.name)
my_dog.bark()

6. continue: 终止当前循环的迭代,进入下一次迭代。

例子:

for num in range(10):
    if num % 2 == 0:
        continue
    print(num)

7. def: 定义一个函数。

例子:

def add(x, y):
    return x + y
    
print(add(3, 4))

8. del: 删除一个变量或对象。

例子:

x = 5
del x

9. elif: 在if语句中使用,用于指定多个条件。

例子:

score = 75
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
else:
    grade = "D"
print(grade)

10. else: 在if语句中使用,用于指定条件为假时的执行语句。

例子:

x = 3
if x > 0:
    print("Positive")
else:
    print("Non-positive")

11. except: 用于捕获异常。

例子:

try:
    x = 1 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")

12. for: 用于遍历可迭代对象的元素。

例子:

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

13. from: 在import语句中使用,用于从模块或包中导入特定的对象。

例子:

from math import sqrt
print(sqrt(16))

14. global: 声明一个全局变量。

例子:

def update_global_x():
    global x
    x = 10

x = 5
update_global_x()
print(x)

15. if: 用于条件判断。

例子:

x = 5
if x > 0:
    print("Positive")
else:
    print("Non-positive")

16. in: 用于判断一个值是否在指定的序列中。

例子:

fruits = ["apple", "banana", "cherry"]
if "banana" in fruits:
    print("Banana is in the list")

17. is: 用于判断两个对象是否引用同一个对象。

例子:

x = [1, 2, 3]
y = x
if x is y:
    print("x is y")

18. lambda: 创建一个简单的匿名函数。

例子:

add = lambda x, y: x + y
print(add(3, 4))

19. not: 逻辑运算符,用于逻辑非操作。

例子:

x = 5
if not x == 0:
    print("x is not zero")

20. or: 逻辑运算符,用于逻辑或操作。

例子:

if x > 0 or y > 0:
    print("Either x or y is positive")

这些是一些最常用的Python关键字,了解和掌握这些关键字的语法和用法对于编写Python代码至关重要。