Reputation: 49
This may seem like a duplicate but the other ones don't apply. So I am trying to make a piggy bank but I cannot figure out how to add a new line while I am using numbers. Right now I am using strings because it is the only way to add a new line. However, when I add the two numbers, it adds them like string. For example, if you entered 5.93 twice. It would print "5.935.93". So, I have to convert it to a string but then I won't be able to add a new line. Here is my code:
def piggybank():
file = open('piggybank.txt','r+')
money = input('How much money are you adding?')
file.write(money + '\n')
for line in file:
money += line
print("You now have:\n", money)
file.close()
In the third line I could make money a float but then in the fourth line I wouldn't be able to add a new line. Can somebody help?
Upvotes: 0
Views: 1199
Reputation: 897
You could keep money
as an Integer
, but when writing, use %s
. Also, if you want to write to a file, you need to make a new variable set to open('piggybank.txt', 'wb')
to write to the file.:
def piggybank():
filew = open('piggybank.txt','wb')
file = open('piggybank.txt','rb')
money = input('How much money are you adding?')
filew.write('%s\n' % money)
for line in file:
money += line
print("You now have:\n%s" % money)
filew.close()
file.close()
Upvotes: 3
Reputation: 3
input()
will give you a str
(string) type object. And you need to convert str
to float
using float()
.By trail and error,I've found following solition.Refernece doc links are strip() doc, open() doc.
def piggybank():
file = open('piggybank.txt','a') #open file for appending to the end of it.
money = input('How much money are you adding? ')
file.write(money + '\n') # Write strings to text file.
file.close()
file = open('piggybank.txt','r')
sum = float(0) # initialize sum with zero value.
for line in file:
sum += float(line.strip('\n')) # srtip '\n' and convert line from str to float.
print("You now have: %s" % sum)
file.close()
Upvotes: 0
Reputation: 1219
You can convert to floats when your doing the math.
float(money) += float(line)
Upvotes: 0
Reputation: 8564
You can do this :
def piggybank():
file = open('piggybank.txt','rb')
money = input('How much money are you adding?')
file.write(str(money) + "\n")
for line in file:
money += float(line.strip())
print("You now have:\n" + str(money))
file.close()
Upvotes: 0