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

相关推荐
lly2024063 小时前
Bootstrap 警告框
开发语言
2601_949146534 小时前
C语言语音通知接口接入教程:如何使用C语言直接调用语音预警API
c语言·开发语言
曹牧4 小时前
Spring Boot:如何测试Java Controller中的POST请求?
java·开发语言
KYGALYX4 小时前
服务异步通信
开发语言·后端·微服务·ruby
zmzb01034 小时前
C++课后习题训练记录Day98
开发语言·c++
ValhallaCoder4 小时前
hot100-二叉树I
数据结构·python·算法·二叉树
猫头虎5 小时前
如何排查并解决项目启动时报错Error encountered while processing: java.io.IOException: closed 的问题
java·开发语言·jvm·spring boot·python·开源·maven
YUJIANYUE5 小时前
PHP纹路验证码
开发语言·php
仟濹5 小时前
【Java基础】多态 | 打卡day2
java·开发语言
孞㐑¥5 小时前
算法——BFS
开发语言·c++·经验分享·笔记·算法