Toán tử một ngôi
Bài học 10 trên 29 trong khóa học Dự án máy tính bằng Python của Coddy.
Như đã thảo luận trong bài học trước, chúng ta có thể thêm hỗ trợ cho toán tử với một số duy nhất, chứ không phải một cặp số.
Dưới đây là một số ví dụ với eval,
eval(['-', 4])->-4eval(['+', 4, ['-', 4]])->0eval(['*', ['+', 4], ['-', 4]])->-16
Thử thách
DễThêm hỗ trợ toán tử một số cho hàm eval.
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 + '"')
def eval(lst):
op = lst[0]
n1 = lst[1]
n2 = lst[2]
if not isinstance(n1, list) and not isinstance(n2, list):
return calc(op, n1, n2)
if isinstance(n1, list):
n1 = eval(n1)
if isinstance(n2, list):
n2 = eval(n2)
return calc(op, n1, n2)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