Một số lỗi thường gặp trong Python

Một số lỗi thường gặp trong Python

Phan Nhật Chánh

Chánh22 tháng 05, 2021

5 min read
·
views
·
likes

Trong quá trình viết code và thực thi một chương trình đôi khi bạn thường khó tránh khỏi một số lỗi như lỗi chính tả hoặc một số lỗi phổ biến khác. Nếu code của bạn không chạy được, thì trình biên dịch python sẽ hiển thị một thông báo, chứa những thông tin phản hồi về vị trí xảy ra sự cố và loại lỗi. Đôi khi, nó cũng sẽ cung cấp cho bạn các đề xuất về cách khắc phục có thể xảy ra. Ở phần trước chúng ta đã tìm hiểu cách xử lý lý ngoại lệ (exception handling). Trong bày này, chúng ta sẽ cùng nhau điểm qua một số lỗi cơ bản và phổ biến nhất khi thực thi một chương trình python.

Trước tiên, bạn mở python bằng cách khởi động Windows PowerShell hoặc Terminal và gõ lệnh python để vào và thực hiện theo các lệnh dưới đây để hiểu rõ hơn các lỗi như thế nào nhé.

SyntaxError

Hãy thử gõ print 'hello word'print 'hello word'enter thử

print 'hello world' File "<stdin>", line 1 print 'hello world' ^ SyntaxError: Missing parentheses in call to 'print'. Did you mean print('hello world')?
print 'hello world' File "<stdin>", line 1 print 'hello world' ^ SyntaxError: Missing parentheses in call to 'print'. Did you mean print('hello world')?

Như bạn có thể thấy, với câu lệnh trên trình biên dich thông báo cho chúng ta đã mắc SyntaxError (lỗi cú pháp) vì chúng ta quên đặt chuỗi trong cặp dấu ngoặc đơn và python đã đề xuất giải pháp.

print ('hello world') hello world
print ('hello world') hello world

Sau khi sửa chữa, code của bạn đã được thực thi mà không gặp trở ngại nào. Hãy xem các loại lỗi khác.

NameError

print(age) Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'age' is not defined
print(age) Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'age' is not defined

Như bạn có thể thấy từ thông báo ở trên, biến age chưa được khai báo. Bây giờ, hãy sửa lỗi này bằng cách khai báo nó và gán vào một giá trị.

age = 25 print(age) 25
age = 25 print(age) 25

Loại lỗi là NameError. Chúng ta đã xử lý lỗi bằng cách khai báo tên biến.

IndexError

numbers = [1, 2, 3, 4, 5] numbers[5] Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: list index out of range
numbers = [1, 2, 3, 4, 5] numbers[5] Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: list index out of range

Trong ví dụ trên, python đã đưa ra lỗi IndexError, vì list chỉ có các phần tử từ 0 đến 4, vì vậy nó nằm ngoài phạm vi.

ModuleNotFoundError

import maths Traceback (most recent call last): File "<stdin>", line 1, in <module> ModuleNotFoundError: No module named 'maths'
import maths Traceback (most recent call last): File "<stdin>", line 1, in <module> ModuleNotFoundError: No module named 'maths'

Trong ví dụ trên, tôi đã cố tình thêm ký tự s bổ sung vào math và lỗi ModuleNotFoundError đã được xuất hiện. Hãy sửa nó bằng cách bỏ ký tự s thừa khỏi math.

import math
import math

Chúng ta đã sửa lỗi trên thành công. Như vậy, khi import một module vào nếu gặp lỗi ModuleNotFoundError thì có thể tên module của bạn sai hoặc không tồn tại.

AttributeError

import math math.PI Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: module 'math' has no attribute 'PI'
import math math.PI Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: module 'math' has no attribute 'PI'

Như bạn có thể thấy, tôi đã cố tình gọi hàm PI thay vì pi. Nó đưa ra một lỗi thuộc tính, có nghĩa là, hàm không tồn tại trong module. Hãy sửa nó bằng cách thay đổi từ PI thành pi.

import math math.pi 3.141592653589793
import math math.pi 3.141592653589793

Bây giờ, khi chúng ta gọi số pi từ module math, chúng ta đã nhận được kết quả.

KeyError

users = {'name':'Chanh', 'age':250, 'country':'Viet Nam'} users['name'] 'Chanh' users['county'] Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'county'
users = {'name':'Chanh', 'age':250, 'country':'Viet Nam'} users['name'] 'Chanh' users['county'] Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'county'

Như bạn có thể thấy, ở ví dụ trên tên khóa country đã viết không đúng (thiếu ký tự r) do đó xuất hiện lỗi KeyError. vì vậy, đây là một lỗi chính và cách khắc phục dễ dàng.

users['country'] 'Viet Nam'
users['country'] 'Viet Nam'

TypeError

4 + '3' Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for +: 'int' and 'str'
4 + '3' Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for +: 'int' and 'str'

Trong ví dụ trên, lỗi TypeErrorxuất hiện bởi vì chúng ta không thể cộng một số cho một chuỗi. Giải pháp đầu tiên sẽ là chuyển đổi chuỗi thành int hoặc float. Một giải pháp khác sẽ là chuyển đổi số thành một chuỗi (kết quả sau đó sẽ là '43').

4 + int('3') 7 4 + float('3') 7.0
4 + int('3') 7 4 + float('3') 7.0

Lỗi đã được xóa và chúng tôi nhận được kết quả như mong đợi.

ImportError

from math import power Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: cannot import name 'power' from 'math' (unknown location)
from math import power Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: cannot import name 'power' from 'math' (unknown location)

Không có hàm nào có tên là power trong module math, nó có một tên khác: pow Hãy sửa lại nó:

from math import pow pow(2,3) 8.0
from math import pow pow(2,3) 8.0

ValueError

int('12a') Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for int() with base 10: '12a'
int('12a') Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for int() with base 10: '12a'

Trong trường hợp này, chúng ta không thể chuyển đổi chuỗi đã cho thành một số, vì có ký tự a trong đó.

ZeroDivisionError

1/0 Traceback (most recent call last): File "<stdin>", line 1, in <module> ZeroDivisionError: division by zero
1/0 Traceback (most recent call last): File "<stdin>", line 1, in <module> ZeroDivisionError: division by zero

Lỗi ZeroDivisionError sẽ xuất hiện vì chúng ta không thể chia một số cho số 0.

Như vậy, chúng ta đã điểm qua một số loại lỗi cơ bản trong ngôn ngữ lập python, hãy xem thêm errors và xử lý ngoại lệ trong python hoặc Errors and Exceptions của python.