(EDITED)
I am trying to make a piggybank by saving the previous money amounts to a file so you can access how much money you have previously had. But, it is giving me an error(see title). Please don't mark this as a duplicate because I already checked the others and they don't apple to my problem. Here is my code:
def piggybank():
newamount = 0.0
file = open('piggybank.txt','r+')
addedmoney = input('How much money are you adding?')
file.write(addedmoney + '\n')
for line in file:
newamount += line
print("You now have:\n", newamount)
Basically I am saying that the new amount is 0. Then I open my file in read and write mode and ask how much the user wants to add. Then I add it to a new line on my file and add up everything in the file. Lastly, I print the sum. However, this does not work because I keep getting the error. Please Help!
(I am sort of a noob at Python and Stack Overflow because I am 13 and just started learning.)
Here is my new 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()
If you look at my original code, I added a newline to money and I did that here as well. However, it adds the money strings as if they were strings so it gives '5.005.00' if you enter 5.00 twice. Does anyone know how to add a new line if you want to print numbers and not strings?
It's because your line is string and newamount is number. That's why you get the error. You have to convert the string to number first before proceeding the math calculation.
def piggybank():
newamount = 0.0
file = open('piggybank.txt', 'r+')
addedmoney = input('How much money are you adding?')
file.write(str(addedmoney) + '\n')
file.seek(0)
for line in file:
newamount += float(line)
print("You now have:\n", newamount)
def piggybank():
newamount = 0.0 # newamount is a floating point number
file = open('piggybank.txt','r+')
addedmoney = input('How much money are you adding?')
file.write(addedmoney + '\n')
for line in file: # line is a string
newamount += line # you are trying to add a floating point number to a string, so the error (I assume) happens here.
print("You now have:\n", newamount)
In conclusion, the operands do not match. First you must convert the string to a floating point number like so:
newamount += float(line.strip()) # strip removes trailing whitespace
On another note, why write addedmoney to the file if you only need to store the total? You can try calculating newamount first and then proceed write that result.
Related
I have written the code below to display the following:
A number of random integers to be chosen by the user
The total of these integers
The total number of numbers
The problem lies in the display of the total, it is concatenating the integers, even though I believe I have used int() correctly.
# This program will write a series of random numbers to a file, and then read and print these numbers
# total of all numbers will be displayed
# number of files read from the file will be displayed
import random
def randomNumberMaker():
random_numbers = open('randoms.txt', 'w')
try:
for i in range(int(input('How many random numbers? :'))):
line_1 = str(random.randint(1, 501))
random_numbers.write(line_1)
print(line_1)
except bad_number:
print("A non integer was entered, sorry.")
random_numbers.close()
randomNumberMaker()
random_number_file = open("randoms.txt", "r")
total= 0
number_of_numbers= 0
line = random_number_file.readline()
while line != "" :
number_of_numbers += 1
number= int (line)
total += number
print(number)
line = random_number_file.readline()
print ("\nThe total number of numbers:" + str(total) +\
"\n There are " + str(number_of_numbers)+ \
" numbers in the file")
Just add endline at the end of each random number.
line_1 = str(random.randint(1, 501)) + '\n'
Since you didn't add any endline character, your input file contains only 1 line of input, and what your code really does is to convert that 1 concatenated string into an int and prints it out.
You used int() correctly, but the problem is in your randoms.txt file. You write all your numbers in a single line without any spaces, so there is no way for the program to know, where to split your numbers. Adding a line break after you write each number fixes the problem:
random_numbers.write(line_1 + "\n")
There is a problem in your randomNumberMaker() function. You are writing all numbers in one line and thus always getting back only one number, which is a textual concatenation of all random numbers.
Change the line
random_numbers.write(line_1)to random_numbers.write(line_1+"\n")and everything will work as expected.
Problem solved! was newfilename[0,3] instead of newfilename[0: 3]
I know this question has been asked before and I have look around on all the answers and the types of problems people have been having related to this error message, but was unable to find anyone with the same type of problem.
I am sowing the whole method just in case. So here is my problem;
When I am trying to get is a substring of "newfilename" using newfilename[int, int] and the compiler keeps thinking I don't have an integer there when I do, at least from my checking I do.
What I'm doing with this code: I am cutting of the end of a filename such as 'foo.txt' to get 'foo' that is saved as newfilename. Then I am adding the number (converted to a string) to the end of it to get 'foo 1' and after that adding back the '.txt' to get the final result of 'foo 1.txt'. The problem occurs when I try to get the substring out and delete the last four characters of the filename to get just 'foo'. After that, I do another check to see if there is a file like that still in the folder and if so I do another set of cutting and pasting to add 1 to the previous file. To be honest, I have not tested of the while loop will work I just thought it should work technically, but my code does not reach that far because of this error lol.
My error:
File "C:/Users/Reaper/IdeaProjects/Curch Rec Managment/Setup.py", line 243, in moveFiles
print(newfilename[0, 3])
TypeError: string indices must be integers
NOTE this error is from when I tried to hard code the numbers it to see if it would work
Here is the current error with the hard code commented out:
newfilename = newfilename[0, int(newfilename.__len__() - 4)] + " 1.m4a"
TypeError: string indices must be integers
What I have tried: I have tried hard coding the numbers is by literally typing in newfilename[0, 7] and still got the same error. I have tried doing this in a separate python file and it seems to work there fine. Also, what is really confusing me is that it works in another part of my program just fine as shown here:
nyear = str(input("Enter new Year: "))
if nyear[0:2] != "20" or nyear.__len__() > 4:
print("Sorry incorrect year. Please try again")
So I have been at it for a while now trying to figure out what in the world is going on and can't get there. Decided I would sleep on it but would post the question just in case. If someone could point out what may be wrong that would be awesome! Or tell me the compilers are just being stupid, well I guess that will do as well.
My function code
def moveFiles(pathList, source, filenameList):
# moves files to new location
# counter keeps track of file name position in list
cnter = 0
for x in pathList:
filename = filenameList[cnter]
#print(x + "\\" + filename)
# new filename
if filename.find("PR") == 0:
newfilename = filename[3:filename.__len__()]
else:
newfilename = filename[2:filename.__len__()]
# checking if file exists and adding numbers to the end if it does
if os.path.isfile(x + "\\" + newfilename):
print("File Name exists!!")
# adding a 1 to the end
print(newfilename)
# PROBLEM ON NEXT TWO LINES, also prob. on any line with the following calls
print(newfilename[0, 3])
newfilename = newfilename[0, int(newfilename.__len__() - 4)] + " 1.m4a"
print("Adding 1:", newfilename)
# once again check if the file exists and adding 1 to the last number
while os.path.isfile(x + "\\" + newfilename):
# me testing if maybe i just can't have math operations withing the substring call
print("File exists again!!")
num = newfilename.__len__() - 6
num2 = newfilename.__len__() - 4
num3 = int(newfilename[num, num2])
num = newfilename.__len__() - 5
newfilename = newfilename[0, num] + str(num3 + 1)
print("Adding 1:", newfilename)
# moving file and deleting prefix
if not os.path.isdir(x):
os.makedirs(x)
os.rename(source + "\\" + filename, x + "\\" + newfilename)
cnter += 1
I think you need this:
print(newfilename[0:3])
I've been writing Python code for only about 4 weeks. I'm writing a little text based game to learn and test everything I know. I can easily make this work with a value entered into the console as an integer, but for whatever reason I can't get my code to work with reading this value from a text file.
Earlier in the program, my code saves a value to a text file, just one value, then later it opens the same text file, over-writes the value with a new value based on a very simple calculation. That calculation is the first value, plus 5. I've spent a bunch of time reading on this site and going through my books and at this point I'm pretty sure I'm just missing something obvious.
The first piece of code that creates the doc and sets the value:
def set_hp(self):
f = open('player_hp.txt', 'w')
self.hitpoints = str(int(self.hitpoints))
f.write(self.hitpoints)
f.close()
This is the trouble section...I have commented the line with the problem.
def camp_fire():
print
print "You stop to build a fire and rest..."
print "Resting will restore your health."
print "You gather wood from the ground around you. You spark\n\
your flint against some tinder. A flame appears.\n\
You sit, and close your eyes in weariness. A peaceful calm takes you\n\
into sleep."
f = open('player_hp.txt', 'r')
orig_hp = f.readlines()
orig_hp = str(orig_hp)
f = open('player_hp.txt', 'w')
new_value = orig_hp + 5 ##this is where my code breaks
new_value = str(int(new_value))
f.write(new_value)
f.close()
print "You have gained 5 hitpoints from resting. Your new HP are {}.".format(new_value)
This is the error I get:
File "C:\Python27\Awaken03.py", line 300, in camp_fire
new_value = orig_hp + 5
TypeError: cannot concatenate 'str' and 'int' objects
I know you can't concatenate a string and an integer, but I keep trying different methods to convert the string to an integer to do the quick math, but I can't seem to get it right.
Error message is clear, you are trying to concatenate string with an integer. You should change the line from:
new_value = orig_hp + 5
To:
new_value = str(int(orig_hp) + 5)
Then you can use above value to write directly into file as a string as:
##new_value = str(int(new_value))## Skip this line
f.write(new_value)
f.readlines() returns a list of lines, in your case something like ['10']. So str(orig_hp) is a textual representation of this list, like '[\'10\']', which you won't be able to interpret as an integer.
You can just use f.read() to read the whole file at once in a string, which will be something like '10', and convert it to a integer:
orig_hp = int(f.read())
choice = input (" ")
choice = int(choice)
if choice == 2:
print ("What class are you in? Please choose (class) 1, 2 or 3.")
Class = int(input ())
#class 1 file
if Class == 1:
c1 = open('class1.csv', 'a+')
ScoreCount = str(ScoreCount)
c1.write(myName + "-" + ScoreCount)
c1.write("\n")
c1.close()
read_c1 = open('class1.csv', 'r')
print (read_c1)
if choice == 3:
row[1]=int(row[1]) #converts the values into int.
row[2]=int(row[2])
row[3]=int(row[3])
row[4]=int(row[4])
if choice == 4:
WMCI= 1
print ("Thank You. Bye!")
So when this code is actually run it outputs an error which I don't understand:
ValueError: invalid literal for int() with base 10:#(myName-score)
How to fix this and what does this error mean in simple terms?
You've got 2 bugs.
The first is when you store your score into the csv, you're converting ScoreCount into a string, and keeping it that way. You need to let the conversion be temporary for just the job:
#class 1 file
if Class == 1:
c1 = open('class1.csv', 'a+')
c1.write(myName + "-" + str(ScoreCount))
c1.write("\n")
c1.close()
read_c1 = open('class1.csv', 'r')
print (read_c1)
That'll fix it with Class 1, you'll need to do 2 & 3. Your second bug is when you're reading the scores from the file, you've stored them as: "Name-5" if the person called Name had scored 5. That means you can't convert them as a whole entity into a number. You'll need to split the number part off. So in min max, where you've got:
row[0] = int (row[0])
It needs to become:
row[0] = int(row[0].split("-")[1])
But from there I can't figure out your logic or what you're trying to achieve in that section of code. It'll get rid of the current error, but that part of your code needs more work.
Explaining the right hand side of the above line of code by building it up:
row[0] # For our example, this will return 'Guido-9'
row[0].split("-") # Splits the string to return ['Guido','9']
row[0].split("-")[1] # Takes the second item and returns '9'
int(row[0].split("-")[1]) # Turns it into a number and returns 9
split("-") is the part you're likely to not have met, it breaks a string up into a list, splitting it at the point of the "-" in our example, but would be at the spaces if the brackets were left empty: split() or any other character you put in the brackets.
You are probably trying to convert something that can't be converted to an int for example
int("h")
This would give the base 10 error which you are getting
Here's my code:
import random
ch1=input("Please enter the name of your first character ")
strch1=(((random.randint(1,12)//(random.randint(1,4))))+10)
sklch1=(((random.randint(1,12)//(random.randint(1,4))))+10)
print("The strength value of "+ch1+" is:")
print (strch1)
print("and the skill value of "+ch1+" is:")
print (sklch1)
ch2=input("Please enter the name of your second character ")
strch2=(((random.randint(1,12)//(random.randint(1,4))))+10)
sklch2=(((random.randint(1,12)//(random.randint(1,4))))+10)
print("The strength value of "+ch2+" is:")
print (strch2)
print("and the skill value of "+ch2+" is:")
print (sklch2)
myFile = open("CharacterSkillAttributes.txt", "wt")
myFile.write("The attributes of "+ch1+" are: /n")
myFile.write("Strength: "+strch1+"/n")
myFile.write("Skill: "+sklch1+"/n")
myFile.write("The attributes of "+ch2+" are: /n")
myFile.write("Strength: "+strch2+"/n")
myFile.write("Skill: "+sklch2+"/n")
myFile.close()
Here's the error:
Traceback (most recent call last):
File "E:\Computing Science\Computing science A453\Task 2\task 2 mostly working (needs 'save to file').py", line 22, in <module>
myFile.write("Strength: "+strch1+"/n")
TypeError: Can't convert 'int' object to str implicitly
I don't want to change the code too much (unless I really have to), just need this problem solved.
Use string formatting to get rid of the error:
file.write('Strength: {0}\n'.format(sklch1))
Obviously you will have to do the same when you write to the file with sklch2.
You should just make a string from your integer variable:
myFile.write("Strength: " + str(strch1) + "/n")
or as suggested Alex use str.format().
The error message tells you exactly that, strch1 is an int and you cannot concatenate it with string directly.
You can do
file.write('Strength: %s\n' % (sklch1))