IndexError:字符串索引超出范围?百吉饼游戏

时间:2019-07-05 11:03:39

标签: python

就像标题一样,它总是显示:

IndexError: string index out of range.

有人可以帮我修复它吗?

clues = []
for i in range(len(guess)):
    if guess[i] == secretNum[i]:
        clues.append('Fermi')
    elif guess[i] in secretNum:
        clues.append('Pico')

...

while guessesTaken <= MAX_GUESS:
        guess = ''
        while len(guess) != NUM_DIGITS or not isOnlyDigits(guess):
            print('Guess #%s: ' % (guessesTaken))
            guess = input()
        clues = getClues(guess, secretNum)
        print(clues)

例外:

Traceback (most recent call last):
  File "/Users/qiyin/Downloads/Python37/bagels.py", line 56, in <module>
    clues = getClues(guess, secretNum)
  File "/Users/qiyin/Downloads/Python37/bagels.py", line 20, in getClues
    if guess[i] == secretNum[i]:

IndexError: string index out of range

2 个答案:

答案 0 :(得分:0)

import random

NUM_DIGITS = 3
MAX_GUESS = 10

def getSecretNum():
    numbers = list(range(10))
    random.shuffle(numbers)
    secretNum = ''
    for i in range(NUM_DIGITS):
        secretNum += str(numbers[i])
        return secretNum

def getClues(guess, secretNum):
    if guess == secretNum:
        return 'You got it!'

    clues = []
    for i in range(len(guess)):
        if guess[i] == secretNum[i]:
            clues.append('Fermi')
        elif guess[i] in secretNum:
            clues.append('Pico')
    if len(clues) == 0:
        return 'Bagels'
    clues.sort()
    return ' '.join(clues)

def isOnlyDigits(num):
    if num == '':
        return False

    for i in num:
        if i not in '0 1 2 3 4 5 6 7 8 9'.split():
            return False
    return True

print('I am thinking of a %s-digit number. Try to guess what it is. ' % (NUM_DIGITS))
print('The clues I give are...')
print('When I say:    That mean:')
print(' Bagels        None of the digits is correct.')
print(' Pico          One digits is correct but in the wrong position.')
print(' Fermi         One digits is correct and in the rigit position.')

while True:
    secretNum = getSecretNum()
    print('I have thought up a number. You have %s guesses to get it.' % (MAX_GUESS))

    guessesTaken = 1
    while guessesTaken <= MAX_GUESS:
        guess = ''
        while len(guess) != NUM_DIGITS or not isOnlyDigits(guess):
            print('Guess #%s: ' % (guessesTaken))
            guess = input()

        clues = getClues(guess, secretNum)
        print(clues)

        guessesTaken += 1

        if guess == secretNum:
            break
        if guessesTaken > MAX_GUESS:
            print('You ran out of guess. The answer was %s.' % (secretNum))

    print('Do you want to play again? (yes or no)')
    if not input().lower().startswith(y):
       break

答案 1 :(得分:0)

您在getSecretNum函数中出现了缩进错误,它将始终为您提供长度等于1的秘密数字,从而使索引超出范围。

事实上,还有其他一些缩进错误! 我为您修复了它们:

import random

NUM_DIGITS = 3
MAX_GUESS = 10


def getSecretNum():
    numbers = list(range(10))
    random.shuffle(numbers)
    secretNum = ''
    for i in range(NUM_DIGITS):
        secretNum += str(numbers[i])
    return secretNum


def getClues(guess, secretNum):
    if guess == secretNum:
        return 'You got it!'

    clues = []
    for i in range(len(guess)):
        if guess[i] == secretNum[i]:
            clues.append('Fermi')
        elif guess[i] in secretNum:
            clues.append('Pico')
    if len(clues) == 0:
        return 'Bagels'
    clues.sort()
    return ' '.join(clues)


def isOnlyDigits(num):
    if num == '':
        return False

    for i in num:
        if i not in '0 1 2 3 4 5 6 7 8 9'.split():
            return False
    return True


print('I am thinking of a %s-digit number. Try to guess what it is. ' % (NUM_DIGITS))
print('The clues I give are...')
print('When I say:    That mean:')
print(' Bagels        None of the digits is correct.')
print(' Pico          One digits is correct but in the wrong position.')
print(' Fermi         One digits is correct and in the rigit position.')

while True:
    secretNum = getSecretNum()
    print('I have thought up a number. You have %s guesses to get it.' % (MAX_GUESS))

    guessesTaken = 1
    while guessesTaken <= MAX_GUESS:
        guess = ''
        while len(guess) != NUM_DIGITS or not isOnlyDigits(guess):
            print('Guess #%s: ' % (guessesTaken))
            guess = input()
            clues = getClues(guess, secretNum)
            print(clues)
            guessesTaken += 1

        if guess == secretNum:
            break
        if guessesTaken > MAX_GUESS:
            print('You ran out of guess. The answer was %s.' % (secretNum))

    print('Do you want to play again? (yes or no)')
    if not input().lower().startswith('y'):
        break