Trường ĐH Công nghệ – Đại học Quốc gia Hà Nội
while True
print("Hello world")
File "script.py", line 1
while True
^
SyntaxError: expected ':'
while True
print("Hello world")
Thiếu dấu hai chấm (:) sau while True.
Nếu một hàm đúng cú pháp, nó “kết thúc” theo cách nào?
| Kiểu kết thúc | Dấu hiệu | Ý nghĩa |
|---|---|---|
| ✅ Bình thường | return | Trả về một giá trị; nếu không có return thì tự trả về None. |
| ⚠️ Bất thường | Exception | Hàm dừng trước khi chạy hết; ngoại lệ được “ném” (một số ngôn ngữ gọi là “throw”). |
Python có nhiều ngoại lệ dựng sẵn để mô tả các lỗi runtime thường gặp.
| Ngoại lệ | Khi nào thường gặp | Gợi ý |
|---|---|---|
| ZeroDivisionError | Chia cho 0 | ⚠️ Kiểm tra mẫu số trước khi chia |
| IndexError | Chỉ số vượt phạm vi danh sách | ✅ Kiểm tra 0 ≤ i < len(lst) |
| ValueError | Giá trị không hợp lệ cho một thao tác | ⚠️ Xác thực đầu vào |
| FileNotFoundError | Không tìm thấy tệp | ✅ Kiểm tra đường dẫn / quyền truy cập |
| TypeError | Thao tác trên kiểu dữ liệu không tương thích | ⚠️ Kiểm tra kiểu/ép kiểu hợp lệ |
Có thể tra thêm trong tài liệu Python.
Khi mẫu số bằng 0, phép chia sẽ gây ngoại lệ.
def divide(a, b):
"""
Divide a by b and return the result.
Raises an exception if b is zero.
"""
return a / b
res = divide(10, 0)
print(res)
import random
the_num = random.randint(1, 100)
guess = input('What number am I thinking of?')
num = int(guess)
if num == the_num:
print('Correct!')
else:
print('Sorry, that was not it.')
def divide(a, b):
if b == 0:
print("Error: Cannot divide by zero.")
return None
return a / b
res = divide(10, 0)
print(res)
import random
the_num = random.randint(1, 100)
guess = input('What number am I thinking of?')
if is_int(guess):
num = int(guess)
if num == the_num:
print('Correct!')
else:
print('Sorry, that was not it.')
else:
print('Sorry, you did not enter a number')
import random
the_num = random.randint(1, 100)
guess = input('What number am I thinking of?')
try:
num = int(guess)
if num == the_num:
print('Correct!')
else:
print('Sorry, that was not it.')
except:
print('Sorry, you did not enter a number')
Output là gì?
def get_item(lst, idx):
try:
return lst[idx]
except:
return 'Out of bounds'
print('Will this run?')
print(get_item([1, 2, 3], 5))
try:
<statements>
except:
<statements>
try:
guess = input("Input an int: ")
num = int(guess)
print('The number is ', num)
except:
print("Error! it's not an int")
print("Done.")
Input an int: 5
The number is 5
Done.
try:
guess = input("Input an int: ")
num = int(guess)
print('The number is ', num)
except:
print("Error! it's not an int")
print("Done.")
Input an int: abc
Error! it's not an int
Done.
try:
guess = input('?')
num = int(guess)
except ValueError:
print('Not an int')
except TypeError:
print()
except:
print('Sorry')
try:
guess = input('?')
num = int(guess)
except ValueError:
print('Not an int')
except TypeError:
print()
from typing import IO
def str_to_int(s):
return int(s)
def func1():
try:
num = str_to_int('apple')
print(num + 1)
except IOError:
print('Not a number')
func1()
try:
<Statements>
except <exn-name>:
<statements>
…
except:
<statements>
finally:
<statements>
def divide(a, b):
try:
result = a/b;
print("Result is ", result)
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
finally:
print("Cleaning up and completing")
res = divide(10, 0)
print(res)
Error: Cannot divide by zero.
Cleaning up and completing
None
def check_password(pwd):
if len(pwd) < 6:
raise ValueError("Password must be at least 6 characters long.")
if pwd.isalpha() or pwd.isdigit():
raise ValueError("Password must contain both letters and numbers.")
print("Password is valid!")
try:
check_password("abc12")
except ValueError as e:
print("Invalid password:", e)
def greet(name):
print("Hello," + name)
for n in ["Roy", 6]:
greet(n)
def greet(name):
assert isinstance(name, str), \
"name must be a string but " \
+ str(name) + " is not"
print("Hello," + name)
for n in ["Roy", 6]:
greet(n)
Đừng hỏi:
“Vì sao code của tôi không làm điều tôi muốn?”
Hãy hỏi:
“Code của tôi đang làm gì?”
Mẹo: dùng repr() để nhìn “dạng lập trình viên”.
def last_name_first(full_name):
print('DEBUG: full_name =' + repr(full_name))
space_index = full_name.index(' ')
print('DEBUG: space_index =' + repr(space_index))
first = full_name[:space_index]
print('DEBUG: first =' + repr(first))
last = full_name[space_index + 1:]
print('DEBUG: last =' + repr(last))
return_value = last + ", " + first
print('DEBUG: return_value = ' + repr(return_value))
return return_value
last_name_first("Toni Marrison")
| Tiêu chí | logging | |
|---|---|---|
| Dùng nhanh | ✅ Rất nhanh, đơn giản | ⚠️ Cần cấu hình ban đầu |
| Quy mô lớn | ❌ Dễ làm “bẩn” output | ✅ Linh hoạt, có mức log |
| Kiểm soát | ❌ Khó bật/tắt có chọn lọc | ✅ Điều chỉnh theo level (INFO, DEBUG…) |
Khi dự án lớn, nên ưu tiên logging.
import logging
logging.basicConfig( level=logging.DEBUG, format="%(levelname)s: %(message)s")
def last_name_first(full_name):
logging.debug('full_name = %r', full_name)
space_index = full_name.index(' ')
logging.debug('space_index = %r', space_index)
first = full_name[:space_index]
logging.debug('first = %r', first)
last = full_name[space_index + 1:]
logging.debug('last = %r', last)
return_value = last + ", " + first
logging.debug('return_value = %r', return_value)
return return_value
Xem thêm: Python logging documentation