python - Struggling to get a simple function running from command line -
i'm trying below function running command line using
python filename.py however, isn't doing want.
could please me out this? i'm sure i'm missing simple...
infile = "" infile = raw_input("enter file name: ") x = open(infile, 'w') def summation(x): sum = 0 in x: sum = sum + return sum if __name__ == "__main__": print(summation(x)) hopefully it's self explanatory i'm trying achieve, in case it's not...
i'm asking raw_input; text file full of numbers (each on it's own line). file should fed variable x used in summation function. finally, loop each value summed , sum returned (and printed in terminal).
there 2 problems:
- you're opening file in write mode. deletes contents of file. drop
"w"parameter. - you can't add strings (as read file) integer. need convert them integers first:
sum += int(i)
also, should close file after you've read contents. , line infile = "" unnecessary.
Comments
Post a Comment