python代码示例

1、打印"Hello, World!"

python 复制代码
print("Hello, World!")

2、基本数学运算

python 复制代码
a = 10
b = 5
print('加:', a + b)
print('减:', a - b)
print('乘:', a * b)
print('除:', a / b)

3、条件语句

python 复制代码
age = 18
if age >= 18:
    print("成年")
else:
    print("未成年")

4、循环语句

python 复制代码
# 使用for循环打印0到9
for i in range(10):
    print(i)

# 使用while循环打印0到9
i = 0
while i < 10:
    print(i)
    i += 1

5、列表推导式

python 复制代码
# 使用列表推导式创建一个包含0到9所有偶数的列表
even_numbers = [x for x in range(10) if x % 2 == 0]
print(even_numbers)

6、函数定义和调用

python 复制代码
def greet(name):
    return "Hello, " + name + "!"

print(greet("Alice"))

7、文件读写

python 复制代码
# 写入文件
with open('example.txt', 'w') as f:
    f.write('Hello, World!')

# 读取文件
with open('example.txt', 'r') as f:
    content = f.read()
    print(content)

8、异常处理

python 复制代码
try:
    result = 10 / 0
except ZeroDivisionError:
    print("不能除以零")

9、类和对象

python 复制代码
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
        
    def greet(self):
        return f"Hello, my name is {self.name} and I am {self.age} years old."

person = Person("Alice", 30)
print(person.greet())

10、网络请求

python 复制代码
import requests

response = requests.get('https://api.github.com')
print(response.json())

以上示例由ChatGPT生成

相关推荐
cup114 小时前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi006 小时前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵8 小时前
用 Python 实现 Take-Away 游戏
python·游戏
copyer_xyf9 小时前
Agent 流程编排
后端·python·agent
copyer_xyf9 小时前
Agent RAG
后端·python·agent
copyer_xyf9 小时前
【RAG】向量数据库:milvus
后端·python·agent
copyer_xyf10 小时前
Agent 记忆管理
后端·python·agent
星云穿梭1 天前
用Python写一个带图形界面的学生管理系统——完整教程
python
金銀銅鐵1 天前
用 Pygame 实现 15 puzzle
python·数学·游戏