如何编写文件而不在循环中重复?如何继续将循环写入文件以及如何在每个条件满足后将初始值重置为 0?
def main():
infile=open("sales.txt","w")
infilelist=[]
#call function
totalsale_each,salesperson=sales(infile,infilelist)
for salesamount in infilelist:
infile.write(salesamount)
infile.close()
def sales(infile, infilelist):
#set initial
t_sales=0
n_sales=int(input("Number of sales"))
while t_sales<n_sales:
#increasement
t_sales+=1
#for loop
for s in range(1,n_sales+1):
totalsale_each=0 #set the acc for total sales by each sales person
sales_person=input("sales person name:")
print("sales for sales no. "+str(s)+"by"+sales_person+":")
infilelist.append(sales_person)
for count in range (1,5): #assuming one sales person can sell max and min of 5item per cust
sales=float(input('sales#' +str(count)+ ':'))
if sales<=300:
t_sales=t_sales+sales
totalsale_each=totalsale_each+sales
if sales>300: #if sales>300, need to change the sales person
#that sales person needs to finish serving the rest of that cust's items
t_sales=t_sales+sales
sales_person=input("another sales pesron")
infilelist.append(sales_person)
infilelist.append(str(totalsale_each)) #to write total sales for each person
return totalsale_each,sales_person
main()
这是我的python测试:
Number of sales: 2
sales person name:A
sales for sales no.1 by A:
sales#1:100
sales#2:150
sales#3:350
another sales pesronB
sales#4:200
sales person name:C
sales for sales no.2 by C:
sales#1:200
sales#2:500
another sales pesronD
sales#3:500
another sales pesronE
sales#4:200
我运行后得到的文件是
A
100.0
250.0
B
250.0
450.0
C
200.0
D
200.0
E
200.0
400.0
但我想要得到的是如下:
A
600
B
200
C
700
D
500
E
200
我该如何纠正?
当销售额超过 300 时询问下一个销售人员后,我无法弄清楚将infilelist.append(sales_person) 和 infilelist.append(totalsale_each)放在哪里。
谢谢