gpt4 book ai didi

python - While 函数中的循环 (Python)

转载 作者:行者123 更新时间:2023-11-30 22:57:59 24 4
gpt4 key购买 nike

所以我基本上创建了我的函数(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()

最佳答案

您必须为用户提供某种方式来声明他们希望停止输入。对于代码来说,一种非常简单的方法是将 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):")

关于python - While 函数中的循环 (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36393249/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com