基本上我想让我的程序做的是:
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]
答案 0 :(得分: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])