While循环函数(Python)
所以我基本上创建了我的函数(def main()、load()、calc()和print()。 但是我不知道如何允许用户在用户想要停止之前,按自己的要求输入信息多少次,就像我输入5次一样,它也会输出5次。我试着将while循环放在def main()函数和load函数中,但当我想停止时它不会停止。有人能帮到吗?谢谢While循环函数(Python),python,loops,while-loop,Python,Loops,While Loop,所以我基本上创建了我的函数(def main()、load()、calc()和print()。 但是我不知道如何允许用户在用户想要停止之前,按自己的要求输入信息多少次,就像我输入5次一样,它也会输出5次。我试着将while循环放在def main()函数和load函数中,但当我想停止时它不会停止。有人能帮到吗?谢谢 def load(): stock_name=input("Enter Stock Name:") num_share=int(input("Enter Numbe
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()
您必须为用户提供某种方式来声明他们希望停止输入。代码的一种非常简单的方式是将
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):")
一个更简单的方法是两个人做以下事情
while True:
<do body>
answer = input("press enter to quit ")
if not answer: break
为True时:
回答=输入(“按回车键退出”)
如果没有,回答:中断
或者
初始化变量并避免使用内部if语句
sentinel = True
while sentinel:
<do body>
sentinel = input("Press enter to quit")
sentinel=True
而哨兵:
sentinel=输入(“按enter键退出”)
如果按enter键,sentinel将设置为空str,这将计算为False,从而结束while循环。尽管函数中的首字母大写方式有所不同
Print()
(func名称中的大写字母与PEP 8相反),但像这样镜像内置内容仍然是一个非常糟糕的选择。我强烈建议更改名称。