简体   繁体   中英

IndexError: list index out of range:

how i can to fix this code
i want to check if the key is like inside the list keys it i also i want if the key is true can user the use the tool if the key is false the user cant use the tool

keys
    {
        "link": "www.xxxxxxxxxxx.com",  
        "key": '34243242354354'
    },
    {
        "link": "www.xxxxxxxxxxx.com",
        "key": '432432534534534'
    },
    {
        "link": "www.xxxxxxxxxxx.com",
        "key": '42345534534'
    }
]
number = 0 
key = input("put the code to use this tool :")
for x in keys:
    number = number + 1 
    if keys[number]["key"] == key:
       print("true")
    else:
       print("false")
      
    

Hi you should try the enumerate() for index loops.

def key_func():
    key = input("put the code to use this tool :")
    for i ,m in enumerate(keys):
        if m['key'] == key:
            return True
    return False

I see here there are 3 problems:

  1. The counter shouldn't be before the execution of the IF statement.
  2. You should put the break after the 'true' statement.
  3. You need a better condition instead of else

You can do this:

number = 0

key = input("put the code to use this tool :")

for x in keys:
    
    if keys[number]["key"] == key:
        print("true")
        break
        
    elif number == (len(keys) - 1):
        print("false")
        
    number = number + 1

Or also better to use the enumerate :

number = 0

key = input("put the code to use this tool :")

for number, x in enumerate(keys):
    
    if keys[number]["key"] == key:
        print("true")
        break
        
    elif number == (len(keys) - 1):
        print("false")

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