2015-02-17 11 views
0

我試圖創建一個具有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() 
+0

我認爲變化必須在「printStock」函數中,作爲else語句,但每次我嘗試更改它時,我都會得到「無效語法」 – 2015-02-18 00:00:38

回答

0

這可能使用max()內置解決。既然您已經知道您搜索的股票的價格,您可以將該價格與p中的最高價格進行比較,如果相等,則打印您的消息,否則搜索該列表。

開始,你叫searchStocks:

price = searchStocks(n,p,stock) 

if max(p) == price: 

    print('There are no stocks higher than',stock) 
else: 

    printStock(n,p,price) 

這應該做的伎倆。

+0

感謝您的格式幫助。我對這位編輯非常陌生,並沒有像我期望的那樣行事。我很感謝幫助。 – wmckevitt 2015-02-18 01:06:22