2016-04-04 179 views
1

所以我基本上創建了我的函數(def main(),load(),calc()和print() 但我不知道如何允許用戶輸入信息的次數儘可能多,直到他們想要停止,就像我輸入了5次,它也會輸出5次,我已經嘗試在def main()函數和加載函數中放置while循環,但它贏了「T停止時,我希望它。有人能幫忙嗎?謝謝!雖然循環功能(Python)

def load(): 

    stock_name=input("Enter Stock Name:") 
    num_share=int(input("Enter Number of shares:")) 
    purchase=float(input("Enter Purchase Price:")) 
    selling_price=float(input("Enter selling price:")) 
    commission=float(input("Enter Commission:")) 

    return stock_name,num_share,purchase,selling_price,commission 

def calc(num_share, purchase, selling_price, commission): 

    paid_stock = num_share * purchase 
    commission_purchase = paid_stock * commission 
    stock_sold = num_share * selling_price 
    commission_sale = stock_sold * commission 
    profit = (stock_sold - commission_sale) - (paid_stock + commission_purchase) 
    return paid_stock, commission_purchase, stock_sold, commission_sale, profit 

def Print(stock_name,paid_stock, commission_purchase, stock_sold, commission_sale, profit): 

    print("Stock Name:",stock_name) 
    print("Amount paid for the stock:\t$",format(paid_stock,'10,.2f')) 
    print("Commission paid on the purchase:$", format(commission_purchase,'10,.2f')) 
    print("Amount the stock sold for:\t$", format(stock_sold,'10,.2f')) 
    print("Commission paid on the sale:\t$", format(commission_sale,'10,.2f')) 
    print("Profit(or loss if negative):\t$", format(profit,'10,.2f')) 

def main(): 

    stock_name,num_share,purchase,selling_price,commission = load() 
    paid_stock,commission_purchase,stock_sold,commission_sale,profit = calc(num_share, purchase, selling_price, commission) 
    Print(stock_name, paid_stock,commission_purchase, stock_sold, commission_sale, profit) 

main() 
+2

儘管您在函數Print()中不同地使用了第一個字母大寫(func名稱中的大小寫與PEP 8相反),但它仍然是一個*非常差的選項來反映內置插件。我*強烈*建議更改名稱。 – Signal

回答

2

你必須給用戶某種方式來聲明他們希望停止輸入。一個很簡單的方法對你的代碼會將main()函數的全部函數包含在while循環:

response = "y" 
while response == "y": 
    stock_name,num_share,purchase,selling_price,commission = load() 
    paid_stock,commission_purchase,stock_sold,commission_sale,profit = calc(num_share, purchase, selling_price, commission) 
    Print(stock_name, paid_stock,commission_purchase, stock_sold, commission_sale, profit) 
    response = input("Continue input? (y/n):") 
1

一個更簡單的方法將是兩個做以下....

while True: 
    <do body> 
    answer = input("press enter to quit ") 
    if not answer: break 

或者 初始化變量,避免內if語句

sentinel = True 
while sentinel: 
    <do body> 
    sentinel = input("Press enter to quit") 

如果輸入被按下時,sentinel被設置爲空str,它將評估爲False,並結束while循環。