Home > other >  Can't figure out how to fix "list index out of range"
Can't figure out how to fix "list index out of range"

Time:10-25

Here is my code:

keys = input('Enter sentence to repeat type')

try:
    keyslist = keys.split(' ')
    length = len(keys)
    while True:
        if keyboard.is_pressed('`'):
            quit()
        
    i = 0
    while i < length:
        keyboard.press(keyslist[i])
        i = i   1
        time.sleep(0.01)
    time.sleep(0.08)
except Exception as exp:
    print(exp)
    selection()

I'm trying to get it to keep typing the same thing over and over. But when I run the code I get "list index out of range" How do I fix this?

CodePudding user response:

Problem is this:

keyslist = keys.split(' ')
length = len(keys)

Since keyslist is defined as being keys but without spaces, it will always be as short as, or shorter than, keys.

For example, if I input 'a s d f', then keyslist = ['a', 's', 'd', 'f'] (four elements), but len(keys) = 7. Note that 7 > 4.

So, when you do this:

i = 0
while i < length:
    keyboard.press(keyslist[i])

eventually, i will reach some number that exceeds the length of keyslist while still not being the length of keys. In my example, that's i = 4 (since lists are zero-indexed, the highest index in keyslist is 3).


Simplest solution is just to replace

length = len(keys)

with

length = len(keyslist)

or just remove that line entirely, and take the length of keyslist at the while loop:

while i < len(keyslist):
  • Related