Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.7k views
in Technique[技术] by (71.8m points)

Creating python calculator using python handling

i've been training in python for a month now (i'm still noobish), and i'm with this project where i want to create calculator using python handlin (.txt files). I know how to create a calculator (program) in python, no problems there, but i've encountered problem using .txt files. So, i have .txt file called expression.txt that contains following:

9-1

6-3

So, it consists out of a number (9), operator (minus -), and number again (1). I need to create a program that reads this expressions, and writes it and its result in a seperate file called result.txt

result.txt should look like this:

9-1=8

6-3=3

This is where i'm stuck, so im really hopeing that someone could give me a push.

class Calculator:

   def sub(self,a,b):

     return a - b

 with open('./expression.txt', 'r') as f:

   lines = f.readlines()

     for l in lines:

        if l[1] == '-':

           print(Calculator.sub(int(l[0]), int(l[2])))



     with open('./result.txt', 'w') as f2:

       f2.write('Test')


    with open('./result.txt', 'r') as f3: 

      print(f3.read())  

Thanks lads!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I'm relatively new to python but this is my shot at your problem;

class Calculator:

    def __init__(self, a, b):
        self.substraction = a - b

    def sub(self):
        return self.substraction


with open('./expression.txt', 'r') as f:

    for line in f.readlines():
        if line[1] == '-':

            with open('./result.txt', 'a') as file:
                file.write(f"{line[0]}-{line[2]}={Calculator(int(line[0]), int(line[2])).sub()}
")

I made some changes to your Calculator class but it's far from optimal, I focused more on the writing into your results file aspect of the problem.

Your main issue is that you're opening your results file in write mode, which overwrites the text file completely, so by the time you reach your next calculation, you'll be deleting the results from the previous one.

This is probably not the best answer but it'll definitely set you off into the right direction.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...