นี่คือสถานการณ์ของฉัน ฉันพยายามสร้างเครื่องคิดเลขขั้นสูงใน python 3.4 ซึ่งคุณสามารถพิมพ์อะไรแบบนี้ได้ '1 + 1' แล้วมันจะให้คำตอบคุณเป็น '2' ตอนนี้ฉันจะอธิบายว่าเครื่องคิดเลขของฉันทำงานอย่างไร ดังนั้นคุณจึงเริ่มต้นด้วยการป้อนสมการทางคณิตศาสตร์ จากนั้นระบบจะนับคำที่คุณป้อนตามช่องว่าง มันทำเช่นนี้เพื่อให้รู้ว่าการวนซ้ำในอนาคตต้องใช้เวลานานแค่ไหน จากนั้นมันจะแยกทุกสิ่งที่คุณป้อน มันแยกมันออกเป็น str's และ int's แต่ทั้งหมดยังคงอยู่ในตัวแปรเดียวกันและทุกอย่างยังคงอยู่ในลำดับ สิ่งที่ฉันประสบปัญหาคือเมื่อตั้งใจจะคำนวณจริงๆ
นี่คือรหัสทั้งหมดของฉัน -
# This is the part were they enter the maths equation
print("-------------------------")
print("Enter the maths equation")
user_input = input("Equation: ")
# This is were it counts all of the words
data_count = user_input.split(" ")
count = data_count.__len__()
# Here is were is splits it into str's and int's
n1 = 0
data = []
if n1 <= count:
for x in user_input.split():
try:
data.append(int(x))
except ValueError:
data.append(x)
n1 += 1
# And this is were it actually calculates everything
number1 = 0
number2 = 0
n1 = 0
x = 0
answer = 0
while n1 <= count:
#The code below checks if it is a number
if data[n1] < 0 or data[n1] > 0:
if x == 0:
number1 = data[n1]
elif x == 1:
number2 = data[n1]
elif data[n1] is "+":
if x == 0:
answer += number1
elif x == 1:
answer += number2
n1 += 1
x += 1
if x > 1:
x = 0
print("Answer =", answer)
แต่ระหว่างการคำนวณมันเกิดความยุ่งเหยิงและทำให้ฉันเกิดข้อผิดพลาด
ข้อผิดพลาด-
if data[n1] < 0 or data[n1] > 0:
TypeError: unorderable types: str() < int()
ใครสามารถเห็นสิ่งที่ฉันทำผิดที่นี่? ขอบคุณ