Python中实现多行语句主要有以下几种方法,可根据具体场景选择合适的方式:
一、使用括号实现多行语句
- 圆括号
可将长表达式拆分到多行书写,例如:
total = (1 + 2 + 3) + (4 + 5 + 6)
my_list = [
'item_one',
'item_two',
'item_three',
更多项...
]
my_dict = {
'key1': 'value1',
'key2': 'value2',
更多键值对...
}
total = item_one + <b class="card40_2411__sup_5321" data-sup="sup">2
item_two + <b class="card40_2411__sup_5321" data-sup="sup">2
item_three
建议 :使用括号或换行符替代反斜杠,以提高代码可读性。
三、使用换行符和括号
通过括号包裹多行代码,并使用换行符分隔,例如:
x = (1 + 2 + 3 + 4 + 5 + 6)
print(x)
这种方式适用于逻辑清晰且行数较少的场景。
四、其他实用技巧
- 分号
允许在一行写多条语句(Python 3.5+),例如:
print("Hello"); print("World")
- 多行输入
若需从标准输入读取多行数据,可使用循环:
for i in range(lines):
text += input(f"输入第{i+1}行内容:") + '\n'
print(text)