2016-04-04 22 views
1

私は基本的に関数def main()、load()、calc()、print()を作成しました。私が5回入力したのと同じように、5回も出力します。def main()関数とload関数にwhileループを入れてみましたが、それは勝ちました私はそれがしたいとき「tは停止。誰かが助けることはできますか?ありがとう!Loop in function(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()の全身をに含めるループ:

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

でも簡単な方法は、2つの次の操作を行うだろう....

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

声明

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

かの場合は、代わり は変数を初期化し、内部を避けますEnterキーが押された場合、sentinelは空のstrに設定され、whileループを終了するとFalseに評価されます。