Python:索引错误:序列下标超出范围

时间:2019-04-29 13:11:41

标签: python python-3.x string

我正在尝试实施单词连锁游戏;这是一种文字游戏,玩家轮流说出以上一个单词的最后一个字母开头的单词。

这是我的代码,我在第9行不断出现索引错误。任何人都可以帮忙。谢谢

这是针对Python 3的:

x = input('Word: ')
xx = 'sample'

while x and xx:
    if x == '':
        break
    xx = input('Word: ')
    if xx == '':
        break 
    while xx[0] != x[-1]:
        print('Invalid word')
        xx = input('Word: ')
    x = input('Word: ')
    if x == '':
        break
    while x[0] != xx[-1]:
        print('Invalid word')
        x = input('Word: ')

这是标准

单词链是一款单词游戏,玩家轮流说出以上一个单词的最后一个字母开头的单词。您可能在长途旅行中玩过这款游戏。

编写一个程序来帮助您播放单词链。您的程序应该用文字阅读,直到输入空白行。如果一个单词不是有效的单词,它应该打印出无效的单词。您的程序应适用于大写和小写单词。

请注意,普通话一词被拒绝,因为它不是以前一个单词的字母e(橙色)开头。下一个单词仍然需要以字母e(从橙色开始)而不是n(从无效词的结尾为普通话)开始。

这里是另一个示例:

Word: tomato
Word: okra
Word: asparagus
Word: seaweed
Word: cake
Invalid word
Word: dried apricots
Word: cake
Invalid word
Word: 

这是最后一个例子。别忘了无论大小写它都应该起作用!

Word: Australia
Word: Antartic
Word: Canada
Word: England
Invalid word
Word: Denmark
Invalid word
Word: 

您将始终读至少两个字。

如果可以的话请帮助

2 个答案:

答案 0 :(得分:0)

您可以将条件简单地包含在while循环中,并且只需将整个代码包括如下:

word     = "elaborate"
old_word = 'sample'

while word != '' and old_word != '':
    old_word = word
    word = input('Word: ')

    if word[0].upper() != old_word[-1].upper():
        print('Invalid word')
        word = input('Word: ')

答案 1 :(得分:0)

这应该可行,请检查代码中的注释!您需要检查输入的单词的长度是否大于1,并跟踪最后一个好单词!

old_word = 'sample'
word = input('Start the chain game, the first word is sample: ')

last_good_word = word
invalid_flag = False

#While the word is not empty
while word != '':

    #If the last word was invalid, use the last good word, else get the latest word
    if invalid_flag:
        old_word = last_good_word
    else:
        old_word = word

    #We get the new word
    word = input('Enter the next word: ')

    #Check if the new word is not a blank string
    if len(word) > 1:
        #If word chain is not met, tell that it is invalid, and set the invalid flag to True
        if word[0].upper() != old_word[-1].upper():
            print('Invalid word')
            invalid_flag = True
            last_good_word = old_word
        #Else set the invalid flag to False
        else:
            invalid_flag = False

输出看起来像

Start the chain game, the first word is sample: echo
Enter the next word: open
Enter the next word: note
Enter the next word: even
Enter the next word: 

Start the chain game, the first word is sample: echo
Enter the next word: open
Enter the next word: yellow
Invalid word
Enter the next word: mellow
Invalid word
Enter the next word: note
Enter the next word: even
Enter the next word: yellow
Invalid word
Enter the next word: mellow
Invalid word
Enter the next word: never
Enter the next word: river
Enter the next word: