我必须编写一个程序,该程序具有用户输入库存信息,计算一些变量,并在while循环中将其吐出。我一直收到这个错误:
NameError: name 'bc' is not defined
为行
amt_paidcomm_onpurch,sold_for,comm_onsale,profit_loss = calc(shares,pp,sp,bc)
以下是代码:
def load():
shares = int(input("Enter Number of shares: "))
pp = float(input("Enter Purchase price: "))
sp = float(input("Enter selling price: "))
bc = float(input("Enter Commission: "))
print("\n")
return shares, pp, sp, bc
def calc(shares,pp,sp,bc):
amt_paid = shares * pp
comm_onpurch = amt_paid * bc
sold_for = shares * sp
comm_onsale = sold_for * bc
profit_loss = (sold_for - comm_onsale) - (amt_paid + comm_onpurch)
return amt_paid, comm_onpurch, sold_for,comm_onsale,profit_loss
def output(name, amt_paid, comm_onpurch, sold_for,comm_onsale,profit_loss):
print("Stock Name: ", name, "\n")
print("Amount paid for the stock: $", format(amt_paid, ',.2f'))
print("Commission paid on purchase: $", format(comm_onpurch, ',.2f'))
print("Amount the stock sold for: $", format(sold_for, ',.2f'))
print("Commission paid on the sale: $", format(comm_onsale, ',.2f'))
print("Profit or loss (if negative): $", format(profit_loss, ',.2f'))
print('\n')
def main():
total=0.0
name=input('Enter stock name or -999 to quit: ')
while name != '-999':
shares,pp,sp,rate=load()
amt_paidcomm_onpurch,sold_for,comm_onsale,profit_loss = calc(shares,pp,sp,bc)
output(name,amt_paid,comm_onpurch,sold_for,comm_onsale,profit_loss)
total=total+profit_loss
name=input("Enter stock name or -999 to quitz: ")
print(total)
main()
谢谢!
答案 0 :(得分:1)
当您致电load()
时,您将变量bc
分配给名称rate
。因此,要么将其分配给名称bc
,要么将calc
函数的调用更改为使用rate
。
即。目前你有:
shares,pp,sp,rate=load()
amt_paidcomm_onpurch,sold_for,comm_onsale,profit_loss = calc(shares,pp,sp,bc)
但是你需要这样的东西:
shares,pp,sp,bc=load()
amt_paidcomm_onpurch,sold_for,comm_onsale,profit_loss = calc(shares,pp,sp,bc)
或:
shares,pp,sp,rate=load()
amt_paidcomm_onpurch,sold_for,comm_onsale,profit_loss = calc(shares,pp,sp,rate)