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

Time:11-09

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}')

CodePudding user response:

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

CodePudding user response:

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

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
  • Related