我試圖創建一個具有4個功能的程序,getStocks,searchStocks,printStocks,然後是使用其他三個函數的主函數。 我的問題是,我想這樣做,以便如果您搜索的股票是最高股票,我希望消息「沒有更高的股票」作爲輸出而不是空白空間出現,但我不確定什麼和我需要添加這樣做。我將「noHigherStocks」變量作爲我想要顯示的消息,但是我要在哪裏實現它?我覺得好像我應該在主函數中使用else語句,但我想不出在何處放置它是有意義的。謝謝閱讀!任何幫助或建議將不勝感激:-)如何在列表中沒有更高的股票時添加「noHigherStocks」功能?
def getStocks():
stockNames = []
stockPrices = []
name = str(input("What is the name of the stock?"))
price = int(input("what is the price of that stock?"))
while name != 'done':
stockNames.append(name)
stockPrices.append(price)
name = str(input("What is the name of the stock?"))
if name != 'done':
price = int(input("what is the price of that stock?"))
return (stockNames, stockPrices)
# returns a single value pertaining to the found price
def searchStocks(stockNames, stockPrices, s):
for i in range (len(stockNames)):
if stockNames[i] == s:
return stockPrices[i]
return -1
# print the names of stocks whose price is higher than p.
def printStock(stockNames, stockPrices, p):
i = 0
while i <len(stockPrices):
if p < stockPrices[i]:
print(stockNames[i])
i = i + 1
return
def main():
n,p = getStocks()
stock = str(input("what stock are you searching for?"))
price = searchStocks(n,p,stock)
printStock(n,p,price)
noStocksHigher = str('There are no stocks higher than',stock)
main()
我認爲變化必須在「printStock」函數中,作爲else語句,但每次我嘗試更改它時,我都會得到「無效語法」 – 2015-02-18 00:00:38