Показаны сообщения с ярлыком калькулятор. Показать все сообщения
Показаны сообщения с ярлыком калькулятор. Показать все сообщения

среда, 22 апреля 2015 г.

Проблема с записью в файл и печатью на экран / The problem with writing to a file and printing it to the screen

Всем привет,  сегодня я озадачился одной проблемой, у меня есть вот такой отрывок кода:
/
Hi everyone, today I've faced the same problem, I have this piece of code:


if r_value==1:
        r_addition = r_digit + r_digit2
        file_calculation.write  ('{0} + {1}' .format( r_digit, r_digit2))
        file_calculation.write (str(' = %s\n' % r_addition))


В током виде как я написал выше - все работает великолепно, но мне кажется так как то не правильно - не красиво. Сейчас я покажу как я хотел сделать:
/
In the current form as I wrote above - it works great, but I think it as something wrong, it is not beautiful. Now I will show how I wanted to do:



if r_value==1:
        r_addition = r_digit + r_digit2
        file_calculation.write  ('{0} + {1} = {3}' .format( r_digit, r_digit2, r_addition))

В таком виде как я написал выше не работает и выдает синтаксическую ошибку с которой я еще не разобрался. Сами понимаете что такая форма записи на много удобнее и приятнее чем то, что я написал выше.
/
In this form, as I wrote above does not work and throws a syntax error which I haven't figured out yet. You know that this form of entry is much easier and more enjoyable than what I wrote above.

Ошибка:
/
Error:
IndexError: tuple index out of range

вторник, 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()