Python常用100个关键字详细示例(1)

2024-04-14 21:54 Python常用100个关键字详细示例(1)已关闭评论

Python并没有100个关键字,Python标准库中定义的关键字数量相对较少,并且是固定的。截止到Python 3.10版本,Python共有35个关键字(不包括保留字)。以下是一个简要的示例集合,涵盖大部分Python关键字:

1、 ifelifelse - 条件判断:

age = 21
if age >= 18:
    print("Adult")
elif age >= 13:
    print("Teenager")
else:
    print("Child")

2、 forin - 遍历序列或可迭代对象:

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

3、 while - 循环:

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

4、 def - 定义函数:

def greet(name):
    print(f"Hello, {name}!")

greet("Alice")

5、 return - 从函数返回值:

def multiply(a, b):
    return a * b

result = multiply(3, 4)
print(result)  # 输出:12

6、 class - 定义类:

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

animal = Animal("Dog")
print(animal.name)

7、 tryexceptfinallyraise - 异常处理:

try:
    raise ValueError("Invalid value!")
except ValueError as ve:
    print(f"Caught an exception: {ve}")
finally:
    print("Cleaning up...")

8、 import - 导入模块:

import os
print(os.getcwd())

9、 global - 声明全局变量:

global_var = 100

def change_global():
    global global_var
    global_var = 200

change_global()
print(global_var)  # 输出:200

10、 nonlocal - 在嵌套函数中访问外层作用域的变量:

def outer():
    x = 1
    def inner():
        nonlocal x
        x += 1
        return x
    return inner()

print(outer())  # 输出:2

当前文章价值5.91元,扫一扫支付后添加微信提供帮助!(如不能解决您的问题,可以申请退款)

你可能感兴趣的文章

来源:每日教程每日一例,深入学习实用技术教程,关注公众号TeachCourse
转载请注明出处: https://www.teachcourse.cn/3328.html ,谢谢支持!

资源分享

分类:python 标签:, ,
ubuntu中创建Python虚拟环境 ubuntu中创建Python虚拟环境
Python开发后端API详细介绍 Python开发后端API详细介绍
ngin异常nginx ngin异常nginx
Android Spinner控件自定义样式分析 Android Spinner控件自定义样式

评论已关闭!