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

Python中常用的关键字介绍

发布时间:2023-12-19 01:27:33

Python是一门使用广泛的编程语言,具有简洁、易读的特点。Python中的关键字是Python语法的组成部分,通过使用关键字,我们可以创建变量、定义函数、控制程序流程等。

下面是Python中常用的关键字及其使用例子:

1. and: 用于逻辑与操作,只有当两个条件都为True时,结果才为True。

a = 10
b = 20

if a > 0 and b > 0:
    print("Both a and b are positive")

2. or: 用于逻辑或操作,只要有一个条件为True,结果就为True。

a = 10
b = 20

if a > 0 or b > 0:
    print("At least one of a and b is positive")

3. not: 用于逻辑非操作,将True变为False,将False变为True。

a = True

if not a:
    print("a is False")

4. if: 用于条件判断,根据条件是否为True执行不同的代码块。

a = 10

if a > 0:
    print("a is positive")
else:
    print("a is not positive")

5. else: 与if配合使用,如果if条件为False,则执行else代码块中的内容。

a = 10

if a > 0:
    print("a is positive")
else:
    print("a is not positive")

6. elif: 与if和else配合使用,可以在多个条件中选择其中一个执行。

a = 10

if a > 0:
    print("a is positive")
elif a == 0:
    print("a is zero")
else:
    print("a is negative")

7. for: 用于循环迭代一个可迭代对象中的元素。

numbers = [1, 2, 3, 4, 5]

for number in numbers:
    print(number)

8. while: 用于循环执行一段代码,直到条件不再满足。

count = 0

while count < 5:
    print(count)
    count += 1

9. break: 用于跳出循环。

numbers = [1, 2, 3, 4, 5]

for number in numbers:
    if number == 3:
        break
    print(number)

10. continue: 用于跳过当前循环的剩余代码,继续执行下一次循环。

numbers = [1, 2, 3, 4, 5]

for number in numbers:
    if number == 3:
        continue
    print(number)

11. def: 用于定义函数。

def add(a, b):
    return a + b

result = add(1, 2)
print(result)

12. return: 用于函数中返回值。

def add(a, b):
    return a + b

result = add(1, 2)
print(result)

13. global: 用于在函数内部声明一个全局变量。

def test():
    global a
    a = 10

test()
print(a)

14. class: 用于定义一个类。

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

    def greet(self):
        print("Hello, my name is", self.name)

person = Person("Alice")
person.greet()

15. import: 用于导入模块,以便使用其中的功能。

import math

print(math.sqrt(16))

16. from: 与import配合使用,从模块中导入指定的功能。

from math import sqrt

print(sqrt(16))

以上是Python中常用的关键字及其使用例子,通过熟悉这些关键字,我们可以更好地理解和编写Python程序。