lundi 25 septembre 2017

Python: How to ask the user for the index of a list

Alright, so I know this is super simple but I am really confused as to how to take a user input as a number and use that number to index from a list with that number. So what I am trying to do is this: Enter your choice: (User enters a 1) You choose 1. Which sentence? (User enters a 0 or whatever number they want within the bounds of how many sentences they enter)

I then just want to use their inputted number and index that from the list. So if they entered these two sentences for their list: good bad

Then when they ask which sentence, and say 1, I want to index sentenceList[1] and print it back to them.

But this needs to be scale-able to any number, so sentenceList[variable], but I do not know how to properly do this.

Thanks, I know this might be confusing.

#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)

Aucun commentaire:

Enregistrer un commentaire