0

I am have been trying to learn how to manipulate lists. Example I have successfully done a simple program that asks the user for a numerical input and returns the corresponding month. Below is an example of what my solution is:

months = ['January', 'February',
          'March', 'April', 'May',
          'June', 'July', 'August',
          'September', 'October', 'November', 'December']

n = int(input("Enter a value between 1 and 12: "))

# Process & Output:
if 1 <= n <= 12:
    print ("The month is", months[n-1])
else:
    print ("Value is out of the range")

My current question is, how would I go about asking the user to pick from the list but by inputting a string rather than an int value?

Example:

subjects= ['Maths','English','Science','History','Business']
n = (input("What is your favourite subject this semester? "))

I would not be able to use the above method because it requires an int value.

martineau
  • 119,623
  • 25
  • 170
  • 301
  • Possible duplicate of https://stackoverflow.com/questions/37565793/how-to-let-the-user-select-an-input-from-a-finite-list – rajeshnair Jul 10 '21 at 20:31
  • Does this answer your question? [How to let the user select an input from a finite list?](https://stackoverflow.com/questions/37565793/how-to-let-the-user-select-an-input-from-a-finite-list) – rajeshnair Jul 10 '21 at 20:33

3 Answers3

1

Here you go:

subjects= ['Maths','English','Science','History','Business']

n = (input("What is your favourite subject this semester? "))

if n in subjects:
    print('great')
else:
    print('even better')
sehan2
  • 1,700
  • 1
  • 10
  • 23
0

If you'd like to check a string input against the list, you can do it simply using in:

subjects = ['Maths','English','Science','History','Business']

subj_in = input("What is your favourite subject this semester? ")

if subj_in in subjects:

    print('Your favorite subject is ', subj_in)

else:

    print('Oh, they offer a course for that?')
DomasAquinas
  • 331
  • 1
  • 7
0

You have already asked the user for the subject. Now you have to find that in subjects list. To do it just use this

if n in subjects: 
    print ("valid subject")
else:
    print("invalid subject")