I wrote a program whose goal is to preserve a numerical value with a further increase in it. However, it seems to me that there is a way to reduce or simplify my program as I plan to use it in another program.

def y(): with open(p, 'r' ,encoding="utf-8") as f: return f.read(32) def u(x): with open(p, 'w' ,encoding="utf-8") as c: x = str(x) c.write(x) def r(): with open(p, 'w' ,encoding="utf-8") as c: c.write('1') p = 'jo.txt' y() x = int(y()) print(x) a = input() if a == 'r': r() print('прогресс сброшен') else: for i in range(10): x+=1 u(x) 

    1 answer 1

    First of all, if you want to continue using this code, it’s better to name the variables in detail, so that you don’t wrestle with what y() means, etc., as well as write comments. Sitting and understanding your code is quite difficult without all this.

    No need to shorten the code if you are going to reuse it. Just put it in a separate module.

     class Saver: encoding = "utf-8" def __init__(self, filename): self.filename = filename def read(self): with open(self.filename, 'r', encoding=self.encoding) as f: return f.read(32) def write(self, value): with open(self.filename, 'w', encoding=self.encoding) as f: f.write(str(value)) def reset(self, default_value=1): self.write(default_value) saver = Saver('jo.txt') x = saver.read() print(x) a = input() if a == 'r': saver.reset() print('прогресс сброшен') else: for i in range(10): x+=1 saver.write(x) 

    If you just want to shorten your code, then I would advise to rewrite the r() function via using u() , as in my example