Nhiều câu lệnh trên một dòng
Dấu chấm phẩy ; cho phép viết nhiều câu lệnh trên một dòng, miễn là không bắt đầu khối mã mới:
import sys; x = 'foo'; sys.stdout.write(x + '\n')
Nhóm câu lệnh (Suites)
Một nhóm các câu lệnh riêng lẻ tạo thành một khối mã (code block) gọi là suite. Các câu lệnh phức hợp như if, while, def, class yêu cầu:
- Header line: dòng tiêu đề bắt đầu bằng từ khóa, kết thúc bằng
: - Suite: một hoặc nhiều dòng thụt lề theo sau header
Cấu trúc chung
if expression:
suite
elif expression:
suite
else:
suite
while expression:
suite
def function_name(parameters):
suite
class ClassName:
suite
Ví dụ thực tế
# if-elif-else suite
score = 85
if score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B'
else:
grade = 'C'
# while suite
count = 0
while count < 5:
print(count)
count += 1
# function suite
def greet(name):
message = f"Xin chào {name}"
return message
Lưu ý: Thụt lề (indentation) là bắt buộc và phải nhất quán trong cùng một suite.