1、打印"Hello, World!"
print("Hello, World!")
2、基本数学运算
a = 10
b = 5
print('加:', a + b)
print('减:', a - b)
print('乘:', a * b)
print('除:', a / b)
3、条件语句
age = 18
if age >= 18:
print("成年")
else:
print("未成年")
4、循环语句
# 使用for循环打印0到9
for i in range(10):
print(i)
# 使用while循环打印0到9
i = 0
while i < 10:
print(i)
i += 1
5、列表推导式
# 使用列表推导式创建一个包含0到9所有偶数的列表
even_numbers = [x for x in range(10) if x % 2 == 0]
print(even_numbers)
6、函数定义和调用
def greet(name):
return "Hello, " + name + "!"
print(greet("Alice"))
7、文件读写
# 写入文件
with open('example.txt', 'w') as f:
f.write('Hello, World!')
# 读取文件
with open('example.txt', 'r') as f:
content = f.read()
print(content)
8、异常处理
try:
result = 10 / 0
except ZeroDivisionError:
print("不能除以零")
9、类和对象
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、网络请求
import requests
response = requests.get('https://api.github.com')
print(response.json())
以上示例由ChatGPT生成