Cấu trúc cơ bản
Bài học 8 trên 29 trong khóa học Dự án máy tính bằng Python của Coddy.
Bước tiếp theo là tính giá trị của danh sách biểu thức.
Cấu trúc cơ bản là - [op, num1, num2]
Một vài ví dụ:
['+', 1, 2]->calc('+', 1, 2)['*', 3, 2]->calc('*', 3, 2)['/', 5.3, 0]->calc('/', 5.3, 0)
Thử thách
Dễtạo hàm eval nhận cấu trúc cơ bản, một danh sách như mô tả ở trên và trả về kết quả tính toán.
Sử dụng hàm calc bạn đã tạo!
Tự làm thử
def calc(op, n1, n2=None):
if not isinstance(n1, int) and not isinstance(n1, float):
raise Exception('Invalid number "' + str(n1) + '"')
if n2 is None:
if op == '+' or op == 'add':
return n1
if op == '-' or op == 'sub':
return -n1
raise Exception('Invalid operator "' + op + '"')
if not isinstance(n2, int) and not isinstance(n2, float):
raise Exception('Invalid number "' + str(n2) + '"')
if op == '+' or op == 'add':
return n1 + n2
if op == '-' or op == 'sub':
return n1 - n2
if op == '*' or op == 'mul':
return n1 * n2
if op == '/' or op == 'div':
if n2 == 0:
raise Exception("Division by zero")
return n1 / n2
if op == '%' or op == 'mod':
if n2 == 0:
raise Exception("Division by zero")
return n1 % n2
if op == '^' or op == 'pow':
return n1 ** n2
raise Exception('Invalid operator "' + op + '"')Tất cả bài học trong Dự án máy tính bằng Python
Tự luyện tập: Trình biên dịch Python online