不能踢出while循环

时间:2016-09-23 04:06:19

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

#Fiery Elsa
#ID:899525
#Homework 2, Program 2


#Initialization
count=0
name=input("Enter stock name OR -999 to Quit:")

#Input
while name!=-999:
    count=count+1
    name=input("Enter stock name OR -999 to Quit:")
    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
print("Stock 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'))

编程循环,但按-999时不会打印输出。我做错了什么?

理想情况下,程序应允许用户输入他/她想要的次数,直到用户完成为止。例如:3组输入产生3组输出。

3 个答案:

答案 0 :(得分:0)

您的问题似乎是name类型为string,但您将其与-999类型int进行比较。

如果您将循环更改为name != "-999",则比较有效。你需要更多地重构你的代码,使它按照你想要的方式运行,但这应该是一个好的开始:)

答案 1 :(得分:0)

您需要在每次输入后评估name的值。

stock_name = []   # make a list for stock name
shares = []   # change also all other input variables into list type

while True:   # this will allow you to loop the input part
    name = input()
    if name != '-999':  # this will evaluate the value of name
        stock_name.append(name)  # this will add your latest name input to the list
        # Do the same to your other inputs
    else:
        break  # exit your while loop

# you need another loop here to do calculations and output
# I think this is where your count variable should go to index your lists

答案 2 :(得分:0)

while name!="-999": #try this one
    count=count+1
    name=input("Enter stock name OR -999 to Quit:")
    shares=int(input("Enter number of shares:"))
    pp=float(input("Enter purchase price:"))
    sp=float(input("Enter selling price:"))
    commission=float(input("Enter commission:"))