无法退出while循环
#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时跳出来打印输出。我究竟做错了什么?无法退出while循环
理想的情况下,程序应该允许用户输入他/她想要的次数,直到用户完成。例如:3组输入产生3组输出。
您的问题似乎是name
是string
,但您将其与-999
进行比较,其类型为int
。
如果你改变你的循环阅读name != "-999"
那么比较的作品。您需要重构一些代码以使其行为符合您的要求,但这应该是一个很好的开始:)
我改变了比较,以反映你的建议,但它仍然没有把我踢出去。它仍然以公司名称读取“-999”。 –
您可以尝试比较name.split(),以防您获取换行符以及输入值? –
-999不发布输出 - 它需要另一组输入,然后帖子输出 –
您需要在每次输入后评估名称的值。
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
我试过了,但它使股票名称“-999” –
每次输入到您的名称变量它会覆盖以前的数据。您需要将其更改为列表类型。 – CpK
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:"))
'name'是从来没有的'int',你需要检查对字符串'“-999'' – AChampion
@AChampion我想‘跳槽’,但没有工作,要么 –
灿” t复制你的错误...改成''-999''终止循环对我来说很好(就像''quit''一样)。 – AChampion