繁体   English   中英

如何使用通过输入添加到 python 中的列表

[英]How do I add to a list in python using via inputs

我是编程的菜鸟。 我想创建一个可以通过输入添加到的开放列表。 我创建的 if 语句不起作用。 即使我在对第二个输入的响应中输入 Y,它也会打印列表。 我确信这有很多问题,但如果有人能告诉我我做错了什么,或者如果有更好的选择,我将不胜感激。

tickers = []
print(f'current tickers list {tickers}')
f = input("please enter a ticker symbol you would like to watch:\n")
tickers.append(f)
q = input("would you like to add another ticker symbol Y or N: ")
if q == 'Y':
    print(f)
    tickers.append(f)
else: 
    print(f'Updated tickers list {tickers}')
tickers = []

while True:
  print(f'current tickers list {tickers}')
  f = input("please enter a ticker symbol you would like to watch:\n")
  tickers.append(f)
  q = input("would you like to add another ticker symbol Y or N: ")
  if q == 'Y':
    pass
  else: 
    print(f'Updated tickers list {tickers}')
    break

想想你想要你的if块完成什么。 你什么时候更新f的值? 你可以尝试例如

if q == 'Y':
    f = input("please enter another ticker symbol you would like to watch:\n")
    tickers.append(f)

尽管正如评论者所说,您可能希望继续观看更多符号——而您可能不知道有多少。 这是使用while循环的绝佳机会:

tickers = []
while True:
  print(f'Current tickers list {tickers}')
  f = input("Please enter a ticker symbol you would like to watch: ")
  tickers.append(f)
  q = input("Would you like to add another ticker symbol? (Y)es or (N)o: ")
  if q.casefold() not in 'no':
    break

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM