0

基本上我希望我的程序做的是:

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.")

无论我做什么,它都会在错误的分支上打印“那不是一个有效的频道”的声明。有没有办法让我的程序使用用户输入搜索我的频道列表/元组?我的频道列表包含变量名 ex。

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

Etc.

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

1 回答 1

1

好的 如果输入是“ch1”并且您希望输出是“Ch1 - Fox News”,那么您的 if 语句不正确。

因为您将 "Ch1" 与 ['Ch1 - Fox News', 'Ch2 - PBS'] 进行比较:

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

因此,要纠正这个问题,您需要使用字典,方法如下:

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', '.')

上层函数是大小写无关的。

更新


随机化:

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

要打印频道列表:

elif choice == "1":
    print("\n")
    for item in channels:
        print(channels[item])
于 2014-11-11T04:58:50.510 回答