简体   繁体   中英

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

I'm a rookie at programming. I want to create an open list that I can add to via inputs. The if statement I created does not work. It prints the list even if I enter Y in my response to the second input. I'm sure there are many issues with this but if someone could tell me what I'm doing wrong or if there is a better alternative it would be greatly appreciated.

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

Think about what you want your if block to accomplish. When do you update the value of f ? You might try eg

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

Though as a commenter remarked, you may want to keep watching more symbols -- and you might not know how many. This is an excellent opportunity to use a while loop:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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