Reputation: 45
I want to avoid recursion, but I'm happy to use for loops. I'm writing to file for a reason, so it must stay.
count =1
b = 1
total = 0
while count <65:
b = b*2
total = total +b
print ("Square number is:",count)
print ("rice on that square",b)
print ("total so far:", total)
count +=1
f = open("rice.csv", "a")
f.write(str(b)+ "\n")
f.close()
print ("all together that ",total,"grains of rice")
kg = total/33000
cost = kg * 1.20
print ("that is £", cost,", thank you very much!")
Upvotes: 0
Views: 79
Reputation: 475
One thing you could do is to use a context manager to open the file. That way it autimatically closes itself.
with open("rice.csv", "a") as file:
file.write(str(b)+ "\n")
Upvotes: 1
Reputation: 448
Note: I changed the mode for open
to w
as you are opening it only once.
total = 0
with open("rice1.csv", 'w') as f:
for i in range(64):
b = 2**(i+1)
total += b
print("Square number is:", i+1)
print("rice on that square",b)
print("total so far:", total)
f.write(str(b)+ "\n")
print ("all together that ",total,"grains of rice")
cost = total/33000 * 1.20
print ("that is £", cost,", thank you very much!")
Upvotes: 2