简体   繁体   中英

Python TypeError: 'str' object cannot be interpreted as an integer

I have this piece of code:

if current_ins[0] == "REPEAT":
    for i in range(current_ins[1]):
        if last_ins != "":
            instructions.append(last_ins)
            if delay != -1:
                instructions.append(["DELAY", delay])
        else:
            print ("ERROR: REPEAT can't be the first instruction")
            sys.exit(-1)

and unfortunately I get this error:

Duck Encoder 0.1.1 by Roger Serentill & GoldraK
Traceback (most recent call last):
  File "D:\devloc\Encoders-decoders\USB-Rubber-Ducky-master\Encoder\Encoder.py", line 379, in <module>
    p.compile(sys.argv)
  File "D:\devloc\Encoders-decoders\USB-Rubber-Ducky-master\Encoder\Encoder.py", line 56, in compile
    instructions = self.__read_file()
  File "D:\devloc\Encoders-decoders\USB-Rubber-Ducky-master\Encoder\Encoder.py", line 263, in __read_file
    for i in range(current_ins[1]):
TypeError: 'str' object cannot be interpreted as an integer

What can I do?

BTW, i'm using Python3.

Try range(len(current_ins[1])): or range(int(current_ins[1])): . It depends on what is inside current_ins[1].

I suppose you are trying to make something like this:-

Inst1
Inst2
REPEAT 5

Now you are trying to repeat previous instructions whatever the "number" you have specified with Repeat.

You can sure just covert it to int, eg int(currenct_inst[1]) , but that's really ambigous. According to the zen of python i advise you to be more explicit, perhaps

if current_instruction[0] = repeat:
    # strip here removes the leading and trailing whitespace
    times_repeat = int(current_instrucitons[1].strip())

If you would like to handle a instruction like REPEAT (::) , then you should take a look at exception handling.

If you're interested, take a look at:-
https://www.programiz.com/python-programming/exception-handling

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM