вторник, 31 марта 2015 г.

Калькулятор с сохранением результата в файл ( разбитый на модули) / Calculator with preservation results to a file (divided into modules)

Всем привет! Сегодня я хочу вам рассказать и показать про следующую эволюцию моего калькулятора,  теперь я в него добавил функцию сохранения результата вычисления в файл и разбил программу на модули - что мне кажется очень облегчает редактирование чтение и добавление нового функционала.

/

Hello everyone! Today I want to tell you about the show and the next evolution of my calculator, now I'm in it added a function of storing the calculation result to a file and the program crashed into modules - which I think makes it very easy to read and edit to add new functionality.



  • Первый модуль - он же модуль запуска программы. 

В нем присутствуют 3 переменных value, digit, digit2 и строка обращения к модулю calculatingresult.calculating_saving_result, вводятся через input 3 значения и передаются на обработку в модуль inputvalue.

Удобный вариант просмотра кода моей программы сохранен тут  http://pastie.org/10064233

/

  • The first module - aka the launcher program.

It contains three variables value, digit, digit2 and string handling module calculatingresult.calculating_saving_result, entered by input values 3 and transferred to the processing module inputvalue.

Convenient way to view my program code stored here http://pastie.org/10064233


form_start_calc.py

import inputvalue
import calculatingresult
FILE_NAME = 'data.txt'

print("select the action and enter the number of action in the field = 1 - addition,")
print("2 - subtraction, 3 - Multiply, 4 - division, 5 - involution")

value = inputvalue.input_value(int,"number of action","message_error")
digit = inputvalue.input_value(float,"enter the first number","message_error")
digit2 = inputvalue.input_value(float, "Enter the second number: ", "message_error2")


calculatingresult.calculating_saving_result (value,digit,digit2)



  • Второй модуль - он создан для ввода переменных и их проверки на ошибки.
Сюда передаются переменные из первого модуля, тут происходит обработка введенных значений.

Удобный вариант просмотра кода моей программы сохранен тут http://pastie.org/10064243

/

  • The second module - it is designed for input variables and error checking.
These variables are transmitted from the first module, then there is a processing input.

Convenient way to view my program code stored here http://pastie.org/10064243


inputvalue.py


import calculatingresult


def input_value(type_value, message, message_error):
    while True:
        try:
            return type_value(input(message))
        except (TypeError, ValueError):
            print(message_error)


  • Третий модуль -  этот код занимается вычислением значений и записью в файл.
Файл для сохранения  "data.txt" который находится в корневой папке программы, мы передаем сюда значения после обработки в предыдущем модуле, переменная value сравнивается в цикле if-elif-else для выбора действия - после произведенных подсчетов, результат сохраняется в файл.

FILE_NAME = 'data.txt' - тут мы переменной назначаем название файла куда будет идти сохранение.

file_calculation = open (FILE_NAME, 'a')  - здесь мы открываем файл для для чтение с флагом 'a' - открытие на до запись, информация добавляется в конец файла.

 file_calculation.write (str(r_addition)) - тут мы с помощью команды write  непосредственно записываем данные в открытый файл.  В скобках указана переменная - результат вычислений.
   file_calculation.close() - закрываем файл ( это необходимо выполнять обязательно ).


Удобный вариант просмотра кода моей программы сохранен тут http://pastie.org/10064251

/

  • The third module - the code deals with the computation of values ​​and writing to a file.
File to save the "data.txt" which is located in the root directory of the program, we give here the values ​​after treatment in the previous module, the variable value is compared in a series of if-elif-else to select action - after making the calculations, the result is stored in the file.

FILE_NAME = 'data.txt' - then we assign a variable name of the file where you want to go save.

file_calculation = open (FILE_NAME, 'a') - here we are opening a file for reading with the flag 'a' - opening up to the record, the information is added to the end of the file.

 file_calculation.write (str (r_addition)) - here we are with the command write directly to write data to an open file. In brackets the variable - the result of calculations.
   file_calculation.close () - close the file (it is necessary to perform required).


Convenient way to view my program code stored here http://pastie.org/10064251

calculatingresult.py
import inputvalue

FILE_NAME = 'data.txt'

def calculating_saving_result (r_value, r_digit, r_digit2):
    file_calculation = open (FILE_NAME, 'a')

    print(r_digit, r_digit2)


    if r_value==1:
        r_addition = r_digit + r_digit2
        file_calculation.write (str(r_addition))
    elif r_value==2:
        r_subtracting = r_digit - r_digit2
        file_calculation.write (str(r_subtracting))
    elif r_value==3:
        r_multiplication = r_digit * r_digit2
        file_calculation.write (str(r_multiplication))
    elif r_value==4:
        r_division = r_digit / r_digit2
        file_calculation.write (str(r_division))
    elif r_value==5:
        r_involution = r_digit ** r_digit2
        file_calculation.write (str(r_involution))
    else:
        file_calculation.write ('fail')
        #print("fail")
    file_calculation.close()



Комментариев нет:

Отправить комментарий