【问题标题】:Converting the contents of a while loop into a function将while循环的内容转换为函数
【发布时间】:2017-02-20 17:04:11
【问题描述】:
#Initialization
name=0
count=0
totalpr=0.0
#Load
name=input("Enter stock name OR -999 to Quit: ")
while name!='-999':
    count=count+1
    shares=int(input("Enter number of shares: "))
    pp=float(input("Enter purchase price: "))
    sp=float(input("Enter selling price: "))
    commission=float(input("Enter commission: "))
    #Calculations
    amount_paid=shares*pp
    commission_paid_purchase=amount_paid*commission
    amount_sold=shares*sp
    commission_paid_sale=amount_sold*commission
    profit_loss=(amount_sold - commission_paid_sale) -(amount_paid + commission_paid_purchase)
    totalpr=totalpr+profit_loss
    #Output
    print("\nStock Name:", name)
    print("Amount paid for the stock:       $",      format(amount_paid, '10,.2f'))
    print("Commission paid on the purchase: $", format(commission_paid_purchase, '10,.2f'))
    print("Amount the stock sold for:       $", format(amount_sold, '10,.2f'))
    print("Commission paid on the sale:     $", format(commission_paid_sale, '10,.2f'))
    print("Profit (or loss if negative):    $", format(profit_loss, '10,.2f'))
    name=input("\nEnter stock name OR -999 to Quit: ")
print("Total Profit is $", format(totalpr, '10,.2f'))

def main()

load() #to input the values
calc()
print()

如您所见,我不知道如何将“#Calculations”段落的内容转换为函数,以便在底部调用它。 “#Load”也是如此(我希望所有输入都在其中,即使它之间有一个while循环)。对于“#Output”,也称为“print()”,我也希望将其转换为函数。

我的底部是正确的,但我不知道如何编辑我的代码以使其整齐地融入函数的形式。代码本身很好,我只需要找到一种方法转换为函数然后调用它。我已经把调用部分放下了,所以我在某种意义上是在倒退。

【问题讨论】:

    标签: python function python-3.x while-loop


    【解决方案1】:

    这对你的几行代码没有意义,因为它会不必要地搞砸事情,但是你去吧:

    def load():
        shares=int(input("Enter number of shares: "))
        pp=float(input("Enter purchase price: "))
        sp=float(input("Enter selling price: "))
        commission=float(input("Enter commission: "))
        return shares, pp, sp, commission
    
    def calc(totalpr):
        amount_paid=shares*pp
        commission_paid_purchase=amount_paid*commission
        amount_sold=shares*sp
        commission_paid_sale=amount_sold*commission
        profit_loss=(amount_sold - commission_paid_sale) -(amount_paid + commission_paid_purchase)
        totalpr+=profit_loss
        return commission_paid_purchase, amount_paid, amount_sold, commission_paid_sale, profit_loss, totalpr
    
    def output():
        print("\nStock Name:", name)
        print("Amount paid for the stock:       $",      format(amount_paid, '10,.2f'))
        print("Commission paid on the purchase: $", format(commission_paid_purchase, '10,.2f'))
        print("Amount the stock sold for:       $", format(amount_sold, '10,.2f'))
        print("Commission paid on the sale:     $", format(commission_paid_sale, '10,.2f'))
        print("Profit (or loss if negative):    $", format(profit_loss, '10,.2f'))
    
    
    if __name__ == "__main__":
        #Initialization
        name=0
        count=0
        totalpr=0.0
        name=input("Enter stock name OR -999 to Quit: ")
        while name!='-999':
            count+=1
            #Load
            shares, pp, sp, commission = load()
            #Calculations
            commission_paid_purchase, amount_paid, amount_sold, commission_paid_sale, profit_loss, totalpr = calc(totalpr)
            #Output
            output()
            name=input("\nEnter stock name OR -999 to Quit: ")
    print("Total Profit is $", format(totalpr, '10,.2f'))
    

    请注意,在 while 循环范围内定义的变量对于从该循环中调用的函数自动可见。

    【讨论】:

    • 我在第 35 行收到一个错误,上面写着“意外缩进”...我尝试缩进所有错误行,但随后程序失败。
    • 以您在这里的方式使用全局变量是一个非常糟糕的主意。 calc 中使用的所有值都应该是参数,而不仅仅是 totalpr
    【解决方案2】:

    这是一种将while循环内部转换为函数,然后使用主函数调用函数的方法。

    您可以将此代码进一步分解为打印功能。只需为此使用 return 语句。

    def calculate(shares,pp,sp,commission,name):
        totalpr = 0
        amount_paid=int(shares)*float(pp)
        commission_paid_purchase=float(amount_paid*commission)
        amount_sold=int(shares)*float(sp)
        commission_paid_sale=float(amount_sold*commission)
        profit_loss=float(amount_sold - commission_paid_sale) -float(amount_paid + commission_paid_purchase)
        totalpr=totalpr+profit_loss
        print("\nStock Name:", name)
        print("Amount paid for the stock:       $",      format(amount_paid, '10,.2f'))
        print("Commission paid on the purchase: $", format(commission_paid_purchase, '10,.2f'))
        print("Amount the stock sold for:       $", format(amount_sold, '10,.2f'))
        print("Commission paid on the sale:     $", format(commission_paid_sale, '10,.2f'))
        print("Profit (or loss if negative):    $", format(profit_loss, '10,.2f'))
        print("Total Profit is $", format(totalpr, '10,.2f'))
    def main():
        name = input("Enter stock:")
        while name != '-999':
            calculate(5,1.22,11.33,11.44,name)
            name = input("Enter stock:")
    main()
    

    【讨论】:

    • 什么进入 def calc(): 和 def print(): ?为什么 def main(): 空白但不是 def calc():?我的问题是 defs main、calc、print 等的内容。另外,我想让它成为 3(加载、计算、打印)加上 main 作为第四个。我该怎么做呢?感谢您的帮助。
    • corinnas 的回答应该会有所帮助。如果您需要帮助进一步理解这一点,请告诉我,我很乐意解释。
    猜你喜欢
    • 2012-06-25
    • 1970-01-01
    • 2015-02-16
    • 1970-01-01
    • 1970-01-01
    • 2014-12-11
    • 2018-02-22
    • 2017-04-26
    • 2018-08-19
    相关资源
    最近更新 更多