Python Index Error

Asked 2 years ago, Updated 2 years ago, 14 views

import sys
class Calc :
    def __init__(self,a,b):
        self.a = a
        self.b = b
    def sum(self):
        return (self.a + self.b)b)
    def sub(self):
        return (self.a - self.b)b)
a = sys.argv[1:3]
a1 = a[1]
a2 = a[2]
calc = Calc(a1,a2)
q = int("Choose an operator\n1. Add 2. Subtract: ")))
if q is 1 :
    print(calc.sum())
elif q is 2 :
    print(calc.sub())
else :
    print("Error")

From

a = sys.argv[1:3]
a1 = a[1]
a2 = a[2]
calc = Calc(a1,a2)

a2 = part a[2]

There was this error. I think it's the right part, but I don't understand why

python

2022-09-21 23:04

2 Answers

Here's a quick way to debug.

a = sys.argv[1:3]
import pdb; add pdb.set_trace() #
a1 = a[1]
a2 = a[2]
calc = Calc(a1,a2)

When you perform the above and enter the factor value, the debugger is performed and the breakpoint is set at a1 = a[1] to stop.

(pdb) p a

If you do so, you can see the value of the a variable with a1 = a[1] stopped.

Verify that the variable value of a is correctly contained.

Then n runs one line at a time c runs continuously, so press c to run the program to the end.


2022-09-21 23:04

The index of the list starts from zero, not from one.

a1 = a[0]    #a1 = a[1]
a2 = a[1]    #a2 = a[2]

Please change it as above.


2022-09-21 23:04

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.