Reputation: 3
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.
Upvotes: 0
Views: 138
Reputation: 579
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")
Upvotes: 0
Reputation: 331
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?')
Upvotes: 0
Reputation: 1835
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')
Upvotes: 1