I have a code that relies on me reading a text file, printing off the numbers where there are numbers, printing off specific error messages where there are strings instead of numbers, then summing ALL the numbers up and printing their sum (then saving ONLY the numbers to a new text file).
I have been attempting this problem for hours, and I have what is written below.
I do not know why my code does not seem to be summing up properly.
And the python code:
f=open("C:\\Users\\Emily\\Documents\\not_just_numbers.txt", "r")
s=f.readlines()
p=str(s)
for line in s:
printnum=0
try:
printnum+=float(line)
print("Adding:", printnum)
except ValueError:
print("Invalid Literal for Int() With Base 10:", ValueError)
for line in s:
if p.isdigit():
total=0
for number in s:
total+=int(number)
print("The sum is:", total)
Every time you enter a new line you reset the total to zero if the number is a digit.
You might want your total to initialize before you enter the loop.
I tried debugging the for loop using the isdigit and isalpha apparently every new line is not considered a digit or alphanumeric these always evaluate to false
As it turns out you don't need the for loop you've done most of the program with your try except statement
Here's how I did it on my system.
So you have to do the following:
Here is one approach:
Here is what you can do:
data.txt:
code:
you can also try this:
here
str.strip([chars])
meansReturn a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped
You are checking the wrong condition:
p
is this:Being a
str
ified version of a list, it will start with a'['
, and hencep.isdigit()
will always be false. You instead want to checkline.isdigit()
, and you want to only initialisetotal
once instead of each time around the loop:Note that by iterating over
f
directly, you also don't need to ever callreadlines()
.