How to check user input in a list/tuple?

1.6k views Asked by At

Basically what I want my program to do is:

new_ch = input("What channel would you like to switch to?")
if new_ch in channels:
      print("You're now on channel,", new_ch,".")
else:
       print("That's not a valid channel.")

No matter what I do, it keeps printing the statement on the false branch "That's not a valid channel". Is there a way I can have my program search my channels list/tuple with the users input? My channels list consists of variable names ex.

Ch1 = "Ch1 - Fox News"
Ch2 = "Ch2 - PBS"

Etc.

channels = [Ch1, Ch2, Ch3, ... Ch10]
1

There are 1 answers

3
thecreator232 On BEST ANSWER

Ok If the input is "ch1" and you expect the output to be "Ch1 - Fox News", then your if statement is incorrect .

Because you are comparing "Ch1" to ['Ch1 - Fox News', 'Ch2 - PBS'] :

>>> channels = [Ch1, Ch2]
>>> channels
['Ch1 - Fox News', 'Ch2 - PBS']

So to correct this you need to use a dictionary, here's how :

Ch1 = "Ch1 - Fox News"
Ch2 = "Ch2 - PBS"
channels = {"CH1":Ch1,"CH2": Ch2}
new_ch = input("What channel would you like to switch to?")
What channel would you like to switch to?"ch1"
if new_ch.upper() in channels:
    print("You're now on channel,", channels[new_ch.upper()],".")
else:
    print("That's not a valid channel.")


 ("You're now on channel,", 'Ch1 - Fox News', '.')

The upper function is just so that it is case independent.

UPDATE


To randomize :

elif choice == "2":
    ch = random.choice(channels.keys())
    print("You're now on channel", channels[ch],".")

To print the list of channels:

elif choice == "1":
    print("\n")
    for item in channels:
        print(channels[item])