以下是一些常用的 Python 代码和语句:
- 打印输出:
print("Hello, world!")
- 变量赋值:
x = 5
y = "John"
- 条件语句:
if x > 10:
print("x is greater than 10")
elif x == 10:
print("x is equal to 10")
else:
print("x is less than 10")
- 循环语句:
for i in range(5):
print(i)
while x < 10:
print(x)
x += 1
- 列表操作:
my_list = [1, 2, 3, 4, 5]
print(my_list[0]) # 输出 1
my_list.append(6) # 添加元素 6 到列表末尾
- 字典操作:
my_dict = {"name": "John", "age": 30, "city": "New York"}
print(my_dict["name"]) # 输出 "John"
my_dict["age"] = 31 # 修改键 "age" 对应的值为 31
- 函数定义:
def my_function(x, y):
return x + y
- 导入模块:
import math
print(math.sqrt(4)) # 输出 2.0