Python:如何向用户询问列表的索引

时间:2017-09-25 08:12:38

标签: python if-statement while-loop user-input

-------回答说,事实证明我做的是正确的事,但有一个不同的错误让我认为这是错误的做法------------- -----

好吧,所以我知道这非常简单但我真的很困惑如何将用户输入作为数字并使用该数字从具有该数字的列表中索引。 所以我想要做的是: 输入您的选择:(用户输入1) 你选择1。 哪句话? (用户在他们输入的句子数的范围内输入0或他们想要的任何数字)

然后我只想使用列表中输入的数字和索引。 所以,如果他们输入这两个句子作为他们的列表: 好 坏

然后,当他们询问哪个句子,然后说1时,我想索引sentenceList [1]并将其打印回来。

但是这需要可以扩展到任何数字,所以sentenceList [variable], 但我不知道如何正确地做到这一点。

谢谢,我知道这可能会令人困惑。

#declare variable
TOTAL_SENTENCES = 5


def main():

 #print greeting
 print ('This program will demonstrate lists')

 #establish array sentences
 sentenceList = list()

 #prompt user for how many sentences to store (assume integer, but if 
 negative, set to 5)
 TOTAL_SENTENCES = int(input('How many sentences? '))
 if TOTAL_SENTENCES < 0:
    TOTAL_SENTENCES = 5
 else:
    pass

 #store in a list in all lower case letters (assume no period at the end)
 while len(sentenceList) < TOTAL_SENTENCES:
    userSentence = input('Enter a sentence: ')
    sentenceList.append(userSentence.lower())

 #print 5 options for the user to choose from (looping this for the total 
 number of sentences)
 for i in range(TOTAL_SENTENCES):
    print ('Enter 1 to see a sentence\n' 'Enter 2 to see the whole list\n'
           'Enter 3 to change a sentence\n' 'Enter 4 to switch words\n'
           'Enter 5 to count letters')

    #prompt user for their choice
    userChoice = int(input('Enter your choice: '))

    #print their choice back to them
    print ('You selected choice' ,userChoice)

    #prompt for which sentence                         
    #CHOICE-1 (pull from the list and print the sentence)

1 个答案:

答案 0 :(得分:0)

现在,在代码的最后一行,如果你想从列表sentenceList中提取一个句子,你可以写一下:

print(sentenceList[userChoice-1])

请注意,我写了userChoice-1。这是因为人们通常会将句子从1编号为N.但Python的内部列表编号从0到N-1。

我希望这能回答你的问题!