-------回答是,我做的是正確的事情,但有一個不同的錯誤,使我認爲這是做錯事情------------------Python:如何向用戶詢問列表的索引
好吧,所以我知道這是超級簡單,但我真的很困惑如何將用戶輸入作爲一個數字,並使用數字從具有該數字的列表中索引。 所以我想要做的是這樣的: 請輸入您的選擇:(用戶輸入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)
我不確定你在這裏遇到麻煩。你已經將輸入轉換爲一個int,那麼爲什麼你不能把它用作索引呢? –
好的,很抱歉,如果它很混亂。如何使用數字的用戶輸入作爲索引中的數字? –
userInput = 1,sentenceList [userInput] –