簡體   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