Search code examples
pythonenumerate

Selecting a string from python enumeration


So, for example let's just say we have a list of strings, like months. We want to only print one of those, based on the input from a variable (or var-1, due to the enumerate function starting with 0 opposed to 1, so the variable is between 0 and 11). So how would I go about selecting one of those based on input and printing it? Keep in mind that doing it with the enumerate function is just my guess, feel free to change it in any way you want but just please, keep it simple here, I'm just starting out.

(Example)

i = input("0-11: ")

months = ["January",.."December]  

so it would somehow use that i to select one of the numbers the func. enumerate provides and print it's string.

PS: I am above sure that there is an easier way of doing this.
PS dos: I apologize if there's already a thread about this but I have no idea how to word this. hh.


Solution

  • Just index the list:

    i = int(input("0-11: "))
    
    months = ["January",.."December"]
    if 0 <= i < 12:
       print(months[i])  
    else:
        print("Must be a number from 0-11")
    

    Or using 1-12:

    i = int(input("1-12: "))
    
    months = ["January",.."December"]
    if 1 <= i <= 12:
       print(months[i-1])  
    else:
        print("Must be a number from 1-12")
    

    You might also want to consider when a user enters something that cannot be cast to int and catch the error