我对我正在做的作业的程序有问题。我的程序中有多个while循环,第一个循环之后的循环似乎会导致第一个循环重新打印我已经输入的数据。
repeat = 'y'
p = 'y'
b = 'y'
s = 'y'
while repeat != 'n':
while p == 'y':
stocksPurchased = float(input("Number of stocks purchased: "))
if stocksPurchased < 0:
print("Negative Values are not allowed. Please re-enter.")
else:
p = 'n'
while b == 'y':
pricePerStockBought = float(input("Amount per stock purchased in $: "))
if pricePerStockBought < 0:
print("Negative Values are not allowed. Please re-enter.")
else:
b = 'n'
while c == 'y':
commissionWhole = float(input("Commission Rate as a percent %: "))
if commissionWhole < 0:
print("Negative Values are not allowed. Please re-enter.")
else:
c = 'n'
while s == 'y':
pricePerStockSold = float(input("Amount per stock sold in $: "))
if pricePerStockSold < 0:
print("Negative Values are not allowed. Please re-enter.")
else:
s = 'n'
commissionRate = commissionWhole/100
grossPurchasePrice = stocksPurchased*pricePerStockBought
purchaseCommission = grossPurchasePrice*commissionRate
totalPurchasePrice = grossPurchasePrice+purchaseCommission
grossSalesPrice = stocksPurchased*pricePerStockSold
saleCommission = grossSalesPrice*commissionRate
netSalePrice = grossSalesPrice-saleCommission
totalCommissionPaid = purchaseCommission+saleCommission
profit = netSalePrice-totalPurchasePrice
profitPercentage = (profit/grossPurchasePrice)*100
print("Commission Fee paid after buying: $", format(purchaseCommission, ',.2f'))
print("Amount stock sold for: $", format(grossSalesPrice, ',.2f'))
print("Commission Fee paid after selling: $", format(saleCommission, ',.2f'))
print("Total Commission Paid: $", format(totalCommissionPaid, ',.2f'))
print("Total Profit made: $", format(profit, ',.2f'))
print("Profit Percentage: %", format(profitPercentage, ',.1f'))
if profitPercentage >= 8:
print("Congrats! You beat the index fund!")
elif 0 <= profitPercentage < 8:
print("Well, you still made money")
elif profitPercentage == 0:
print("Nothing gained, nothing lost")
else:
print("Perhaps the stock market isn't for you")
if totalCommissionPaid > profit:
print("Seems you should either pick different stocks, or find a cheaper broker")
repeat = input("Would you like to go again y/n?: ")如果我在这里输入y,程序会重复,而不是重新提示数字,而是重新打印上一次运行中的数据。
例如,如果我分别输入数字:1000, 10, 5, 15,它只会重印以前相同的数字。

发布于 2018-04-02 03:50:02
将p、b、c和s的值设置为'y'。
发布于 2018-04-02 03:50:02
为了解决这个问题,您需要在while循环中初始化变量。这样,每当您完成循环的迭代时,您的变量就会重新启动,因此满足了下一个循环的条件。所以你的代码应该是:
while repeat != 'n':
repeat = 'y'
p = 'y'
b = 'y'
s = 'y'
c ='y'
while p == 'y':
stocksPurchased=float(input("Number of stocks purchased: "))
if stocksPurchased < 0:
print("Negative Values are not allowed. Please re-enter.")
else:
p = 'n'最重要的是,您应该修复您的缩进,因为它似乎有点差。
发布于 2018-04-02 03:51:28
你需要写这几行:
p = 'y'
b = 'y'
s = 'y'在主while循环中。然后它就能解决你的问题。
https://stackoverflow.com/questions/49605003
复制相似问题