Python: ข้อผิดพลาดประเภท

นี่คือสถานการณ์ของฉัน ฉันพยายามสร้างเครื่องคิดเลขขั้นสูงใน 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()

ใครสามารถเห็นสิ่งที่ฉันทำผิดที่นี่? ขอบคุณ


person Jonty Morris    schedule 11.11.2014    source แหล่งที่มา
comment
#โค้ดด้านล่างตรวจสอบว่าเป็นตัวเลขหรือไม่ ยกเว้นว่าไม่ใช่   -  person Ignacio Vazquez-Abrams    schedule 11.11.2014
comment
จริงหรือ โอเค ถ้ามันไม่เป็นเช่นนั้น คุณจะมีวิธีแก้ไขมันไหม?   -  person Jonty Morris    schedule 11.11.2014


คำตอบ (1)


เมื่อคุณเปรียบเทียบสตริงกับจำนวนเต็ม ปัญหานี้จะเกิดขึ้น Python ไม่เดา แต่มันเกิดข้อผิดพลาด เพื่อแก้ไขปัญหานี้ เพียงโทร int() เพื่อแปลงสตริงของคุณเป็นจำนวนเต็ม:

int(input(...))

ดังนั้น ข้อความที่ถูกแก้ไขควรเป็น:

if int(data[n1]) < 0 or int(data[n1]) > 0:
person Dr. Debasish Jana    schedule 11.11.2014
comment
ไม่ ไม่ใช่สิ่งนี้ อ่านวงข้างบน - person Ignacio Vazquez-Abrams; 11.11.2014