2016-11-11 5 views
0

Моя программа предназначена для генерации случайного пароля длиной 5 символов с использованием символов, приведенных ниже в переменной char. Проблема в том, что я верю в randint и не могу понять, почему.Python - IndexError: индекс строки вне диапазона

from random import randint 
print("1. 5 Letters") 
enc = input("Please enter your desired option: ") 
if enc == "1": 
    chars = str() 
    for i in range (1, 6+1): 
     chars += str("\"~`<>.,?/:;}{[]+_=-)(*&^%$£@!±§qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890" [randint(1, 67)]) 
    print("Your password is: " + chars) 
    print("\n") 

    yon = input("Do you want a new password (yes or no): ") 
    if yon == "yes": 

     np = int(input("How many new passwords do you want: ")) 
     print("\n") 
     count = 0 
     for i in range(1, np+1): 
      count += 1 
      chars = str() 
      for i in range (1, 6 + 1): 
       chars += "\"~`<>.,?/:;}{[]+_=-)(*&^%$£@!±§qwertyuiopasdfghjklzxcvbnm1234567890" [randint(1, 67)] 
      print("Your password is : " + str(chars) + " This is password number: " + str(count) + "/" + str(np)) 
      print("\n") 
    elif yon == "no": 
     print("Goodbye.") 

Я получаю эту ошибку после получения части, в которой моя программа генерирует дополнительные пароли.

Traceback (most recent call last): 
    File "/Users/rogerhylton/Desktop/Coding/Python/te.py", line 25, in <module> 
    chars += "\"~`<>.,?/:;}{[]+_=-)(*&^%$£@!±§qwertyuiopasdfghjklzxcvbnm1234567890" [randint(1, 67)] 
IndexError: string index out of range 

ответ

2
>>> from random import randint 
>>> randint(1, 3) 
2 
>>> randint(1, 3) 
3 
>>> help(randint) 
Help on method randint in module random: 

randint(a, b) method of random.Random instance 
    Return random integer in range [a, b], including both end points. 

Поскольку ваша строка имеет длину 67, наибольший индекс может занять 66, но иногда пытаются получить индекс 67, отсюда и IndexError.

Кроме того, первый символ, полученный по индексу 0:

>>> "abc"[0] 
'a' 
>>> "abc"[1] 
'b' 
>>> "abc"[2] 
'c' 
>>> "abc"[3] 
Traceback (most recent call last): 
    File "<input>", line 1, in <module> 
IndexError: string index out of range 

Поэтому вы должны использовать [randint(0, 66)].

Или еще лучше:

# Declare this variable once 
possible_chars = "\"~`<>.,?/:;}{[]+_=-)(*&^%$£@!±§qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890" 

# Use this line in both places instead of duplicating the string literal 
char = possible_chars[randint(0, len(possible_chars) - 1)] 

или использовать эту функцию в обоих местах:

def get_random_char(): 
    possible_chars = "\"~`<>.,?/:;}{[]+_=-)(*&^%$£@!±§qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890" 
    return possible_chars[randint(0, len(possible_chars) - 1)] 

и, наконец:

from random import choice 

def get_random_char(): 
    possible_chars = "\"~`<>.,?/:;}{[]+_=-)(*&^%$£@!±§qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890" 
    return choice(possible_chars) 
+0

OP * должны * использовать динамическое значение вместо заданного целого числа, но вы не правы. –

+0

@SterlingArcher сделано. –

0

Там см 2 вещи в вашем коде.

  1. Нет необходимости явно указывать chars = str() u объявили эту переменную дважды.
  2. В строке 25: положить str() вне стоимости chars т.е.

chars += str("\"~<>.,?/:;}{[]+_=-)(*&^%$ £@!+§qwertyuiopasdfghjklzxcvbnm1234567890" [randint(1, 67)])

Смежные вопросы