Khi cần lấy số lượng cụ thể lũy thừa của một số, dùng toán tử ** kết hợp list comprehension.
Ví dụ
n = 4
print("The value n is:")
print(n)
k = 5
print("The value of k is:")
print(k)
result = [n ** index for index in range(0, k)]
print("The square values of N till K:")
print(result)
Đầu ra
The value n is: 4 The value of k is: 5 The square values of N till K: [1, 4, 16, 64, 256]
Giải thích
- Định nghĩa n, k, hiển thị.
- List comprehension lặp range(k), dùng
**tính lũy thừa. - Gán biến, hiển thị.