虽然循环不打印输入,但退出时不会中断while循环

时间:2016-09-23 22:33:57

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

//  v--- check that it exists
if (ctyIndem[v] && a.FIPS == ctyIndem[v].id) { //County is present, then is ok
  console.log(ctyIndem[v].id); 
 } else {//County not present, add new info

正如你所看到的那样,我正在为谷歌和亚马逊输入股票,但当我运行“-999”以突破while循环时,它们不会被打印出来。相反,它认为“-999”是一个股票名称,当你为它输入假数字并且打印它们时退出。我无法弄清楚我做错了什么。

3 个答案:

答案 0 :(得分:0)

一旦你得到-999,就应该突破循环,而不是一直持续当前的迭代直到结束。

其次,您可以收集字符串中的项目,并仅在循环后输出:

#Initialization
count=0
name=0
result = ''
#Input
while True:
    count=count+1
    test=input("Enter stock name OR -999 to Quit:")
    if test=='-999': break
    name=test
    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)

    #Output
    result += """
Stock Name: {}
Amount paid for the stock:       ${:06.2f}
Commission paid on the purchase: ${:06.2f}
Amount the stock sold for:       ${:06.2f}
Commission paid on the sale:     ${:06.2f}
Profit (or loss if negative):    ${:06.2f}
""".format(name, amount_paid, commission_paid_purchase, amount_sold, commission_paid_sale, profit_loss)

print (result);

repl.it

上查看它

答案 1 :(得分:0)

在输入name之前,您正在检查-999 的值。将你的循环改为:

while True:
    x = input("Enter stock name OR -999 to Quit:")
    if x == '-999':
        break
    count = count+1
    name = x
    shares = int(input("Enter number of shares:"))
    pp = float(input("Enter purchase price:"))
    sp = float(input("Enter selling price:"))
    commission = float(input("Enter commission:"))

也就是说,您的脚本只会处理您输入的 last 股票的信息;循环的每次迭代都会覆盖namesharesppspcommission的上一个值。您也想要在循环内移动计算,或者将 all 保存在列表或字典中输入的数据,以便以后可以访问它。

答案 2 :(得分:0)

在您退出循环时,“ - 999”是存储为股票名称的值,因此这是打印的内容。其他值属于您在输入“ - 之前输入的信息的股票” - 999“。