Reputation: 1
This is my code
Apple = ['Aapl', 300]
Microsoft = ['Msft', 180]
#List of Stocks in the Index
stocks = [Apple, Microsoft]
#Company Lookup to Find Ticker Symbol or Share Price
def lookup(stock):
return stock
n=0
if stock == stocks[n]:
stock = stock
else:
n=n+1
stock = (input("What company would you like to look up?"))
lookup(stock)
print(stock)
##Non working
select = input("Would you like their ticker (1) or price (2)?")
if select == 1:
print(stock[0])
else:
print(stock[1])
Currently what I'm getting is the 1st or 2nd letter in stock I.e. A or P for Apple, M or I for Microsoft. I want Python to recognize that the value of the variable "stock" is actually and index and account for the 0 or 1 position in the index. Any help?
Upvotes: 0
Views: 58
Reputation: 444
There are two problems. As pointed out, the lookup
function returns the string "Aapl"
or "Msft"
, rather than the list. Then, the value of any input
statement is a string, but your condition is comparing it to an int, so it'll always return False
. Therefore, it'll always print the second element of the stock
string, which is either a
or s
.
To fix this, you could do this:
def lookup(stock):
for stock_i in stocks:
if stock == stock_i[0]:
retstock = stock_i
return(retstock)
stock = (input("What company would you like to look up?"))
stock = lookup(stock)
print(stock[1])
select = input("Would you like their ticker (1) or price (2)?")
if select == "1":
print(stock[0])
elif select == "2":
print(stock[1])
Upvotes: 0
Reputation: 2292
I think what you might be after is something like this:
Apple = ['Aapl', 300]
Microsoft = ['Msft', 180]
#List of Stocks in the Index
stocks = {'Apple': Apple, 'Microsoft': Microsoft}
#Company Lookup to Find Ticker Symbol or Share Price
def lookup(stock_input):
if stock_input in stocks:
return stocks[stock_input]
else:
print('{0} not found in {1}'.format(stock_input, stocks.keys()))
stock_input = input("What company would you like to look up?")
stock = lookup(stock_input)
print(stock)
select = int(input("Would you like their ticker (1) or price (2)?"))
if select == 1:
print(stock[0])
else:
print(stock[1])
Upvotes: 2