【问题标题】:While Loop in function ( Python )函数中的while循环(Python)
【发布时间】:2016-07-23 10:32:58
【问题描述】:

所以我基本上创建了我的函数(def main()、load()、calc() 和 print()。 但我不知道如何允许用户输入他/她想要的多次信息,直到他们想要停止。就像我他们输入 5 次一样,它也会输出 5 次。我已经尝试将 while 循环放在 def main() 函数和 load 函数中,但是当我想要它时它不会停止。有人可以帮忙吗?谢谢!

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()

【问题讨论】:

  • 尽管您在函数Print() 中的首字母大写不同(函数名称中的大写字母反对 PEP 8),但镜像内置函数仍然是一个非常糟糕的选择像那样。我强烈建议更改名称。

标签: python loops while-loop


【解决方案1】:

您必须给用户某种方式来声明他们希望停止输入。代码的一个非常简单的方法是在 while 循环中包含 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):")

【讨论】:

    【解决方案2】:

    一个更简单的方法是两个做以下......

    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 循环。

    【讨论】:

      猜你喜欢
      • 2014-11-02
      • 1970-01-01
      • 2018-09-15
      • 2021-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-03
      相关资源
      最近更新 更多