在Python命令行中,你可以通过以下几种方法来编写多行代码:
1. 使用分号(`;`)分隔语句:
print('Hello, world!');print('Python is fun!')
2. 使用三引号(`'''` 或 `"""`)创建多行字符串:
multi_line_string = """Hello,
world!
Python is fun!"""
3. 使用括号(`(` 和 `)`)和换行符来组织代码块:
if True:
print('This is a multi-line
statement using parentheses.')
squares = [x 2 for x in range(10) if x % 2 == 0]
5. 使用`exec()`或`eval()`函数执行字符串形式的Python代码:
exec('a, b = 1;b, a = a, b')
6. 在交互式命令行中,使用连续两个回车来结束输入的多行代码:
print('Hello, world!')
print('Python is fun!')
print('This is the end of the multi-line input.')
注意:在Python中,语句结束不需要分号,但在换行时通常需要使用分号。最后一行代码不要求必须有分号,但加上也不会出错