Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Dòng và Thụt Lề (Lines and Indentation) trong Python

Python không dùng dấu ngoặc nhọn { } để đánh dấu khối mã. Thay vào đó, Python dùng thụt lề (indentation) - số khoảng trắng ở đầu dòng - để xác định khối lệnh. Điều này được thực thi nghiêm ngặt.

Quy tắc cơ bản

  • Số khoảng trắng trong thụt lề có thể tùy chọn (thường 4 spaces)
  • Tất cả câu lệnh trong cùng một khối phải thụt lề như nhau
  • Không được trộn tab và space

Ví dụ đúng

if True:
    print("True")
else:
    print("False")

Ví dụ sai (lỗi IndentationError)

if True:
    print("Answer")
print("True")   # Sai: không cùng thụt lề với if
else:
    print("Answer")
    print("False")

Ví dụ nhiều khối lồng nhau

#!/usr/bin/python
import sys

try:
    # open file stream
    file = open(file_name, "w")
except IOError:
    print("There was an error writing to", file_name)
    sys.exit()

print("Enter '", file_finish, "' When finished")
while file_text != file_finish:
    file_text = raw_input("Enter text: ")
    if file_text == file_finish:
        # close the file
        file.close()
        break
    file.write(file_text)
    file.write("\n")

file.close()

Lưu ý quan trọng

  • Dùng 4 spaces cho mỗi cấp thụt lề (PEP 8)
  • Cấu hình editor: Tab = 4 spaces, Insert spaces
  • Khi copy code từ web, hãy kiểm tra thụt lề