Split() trong python

Hi m.n mình đang học python và gặp một lỗi nhỏ trong khi thực hành mong m.n giúp đỡ :slight_smile:
Khi mình để code vậy thì chạy được :slight_smile:

num1, operator, num2 = input("Enter Calculation:".split())
num1 = int(num1)
num2 = int(num2)


if operator == '+':
    print("{} + {} = {}".format(num1, num2, num1 + num2))
elif operator == '-':
    print("{} - {} = {}".format(num1, num2, num1 - num2))
elif operator == '/' :
    print("{}-{} ={}".format(num1, num2, num1 / num2))
elif operator == '*':
    print("{} * {} = {}".format(num1, num2, num1*num2))
elif operator == '%':
    print("{} % {} = {}".format(num1, num2, num1%num2))
else:
    print("This is not result!!!! Please enter again. Thank you.")

Nhưng khi sửa lại thành :slight_smile:

num1, operator, num2 = input("Enter Calculation:").split()
num1 = int(num1)
num2 = int(num2)

if operator == '+':
    print("{} + {} = {}".format(num1, num2, num1 + num2))
elif operator == '-':
    print("{} - {} = {}".format(num1, num2, num1 - num2))
elif operator == '/' :
    print("{}-{} ={}".format(num1, num2, num1 / num2))
elif operator == '*':
    print("{} * {} = {}".format(num1, num2, num1*num2))
elif operator == '%':
    print("{} % {} = {}".format(num1, num2, num1%num2))
else:
    print("This is not result!!!! Please enter again. Thank you.")

Lại bị lỗi :slight_smile:

  File "C:/Users/ICT/PycharmProjects/untitled/ex1.py", line 2, in <module>
    num1, operator, num2 = input('Enter Calculation:').split()
ValueError: not enough values to unpack (expected 3, got 1)

ps: có bạn nào muốn học python cùng mình ko ạ.(cách học là: cố sửa cho 1 code nào đó sai và người kia tìm lỗi )

Dòng input("Enter Calculation:").split() của bạn là nó split chuỗi đầu vào. Bạn thử nhập dữ liệu theo kiểu “1 + 2” xem nhé.

2 Likes

Thks Bạn Ms phát hiện ra.

Chuỗi split mặc định sẽ split theo khoảng trắng, nên nếu bạn nhập không khoảng trắng thì chỉ ra được 1 phần tử thôi

1 Like
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?