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生成

相关推荐
Leighteen15 分钟前
`try-finally` 里的 `return`:为什么 `finally` 会悄悄改掉返回值、吞掉异常
java·开发语言
05664617 分钟前
Python康复训练——控制流与函数
开发语言·python·学习
峥无30 分钟前
C++11 深度详解:现代 C++ 基石全梳理
开发语言·c++·笔记
阿米亚波41 分钟前
【C++ STL】std::unordered_multimap
开发语言·数据结构·c++·笔记·stl
天使day43 分钟前
FastAPI快速入门
python·fastapi
databook1 小时前
用相关性分析消除“冗余特征”
python·机器学习·scikit-learn
SomeB1oody1 小时前
【RustyML入门】1.0. 快速上手
开发语言·后端·机器学习·rust·教程
狗凯之家源码网1 小时前
短剧系统搭建实战:源码功能与商业变现效果全景展示
开发语言·php
幻想时空2 小时前
地图数据采集
python
梦想不只是梦与想2 小时前
Python 中的类型判断方法
python·type·isinstance