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

среда, 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

понедельник, 20 апреля 2015 г.

Вывод из файла / Input from file

Доброе утро, я давно не писал ничего так как был приступ лени, выходные выбили меня из колеи и мне тяжело было вернуться.

Сегодня я дописал вывод информации из файла к калькулятору из предыдущей статьи (Калькулятор),  сам по себе вывод очень прост, сначала делаем открытие файла на чтение после с помощью for считываем строки из файла и печатаем на экран.


Если вы меня читаете напишите пожалуйста в комментариях, что еще добавить к калькулятору ??


/


Good morning, I have not written anything since had an attack of laziness, weekend knocked me off balance and it was hard to go back.

Today I finished the withdrawal of the information from the file to the calculator from the previous article (Calculator), by itself, the conclusion is very simple, first make opening the file for reading after using for read lines from file and print to the screen.

If you read me please write in the comments what else to add to the calculator ??




# -*- coding: utf-8 -*- #Выставляем кодировку / Set the encoding

FILE_NAME = 'data.txt'  #Присваиваем переменной название файла с результатами /
                        #Assign to the variable the name of the results file
def printfile():
    file_print = open (FILE_NAME,'r') #Открываем на чтение / Opened for reading
    for line in file_print:   #Считываем строки из файла / Read lines from file
        print (line)   #Печатаем на экран / Printed on the screen
    file_print.close() #Закрываем сессию / Close the session

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



суббота, 14 марта 2015 г.

Python, Конструкция try - except для обработки исключений / Python, structure try - except for exception handling

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

Как сделать возвращение к к началу если произошла ошибка ? 

код выложен на внешний ресурс для удобного просмотра - не смог встроить сюда :( 

/

Today I want to share with you my example structure exceptions, the example is simple and does not show the full functionality - as I myself have not yet fully understood.
The problem is that while I handle the error can not go back to the previous step. For example I enter the product price (enter the numbers you need to do), and I enter the letters - an error is detected, but instead of what would bring me back to the same input data, the program continues to run on.

How to make a return to the beginning if an error occurs?

code is laid out to an external resource for easy viewing - could not build here :(

try:
    a=float(input("the price of 1 kg of sweets: "))
except (TypeError, ValueError):
    print("error, enter the number")
try:
    c=float(input("How many grams of sweets weigh ? "))
except (TypeError, ValueError):
    print("error, enter the number")
try:
    b=float(input("the price of 1 kg of biscuits: "))
except (TypeError, ValueError):
    print("error, enter the number")
try:
    d=float(input("How many grams weigh cookies ? "))
except (TypeError, ValueError):
    print("error, enter the number")

x=(a/1000)*c     #cost calculation
y=(b/1000)*d    #cost calculation
z=x+y                  #the sum of the prices of purchases

print ("The cost of",c,"grams of sweets:",x,"rubles")
print ("The cost of",d,"grams of biscuits:",y,"rubles")
print ("The total purchase price of:",z,"rubles")

Расскажу про  эту конструкцию, объявления блока конструкции обязательно начинает с try: 
в ней так же должна присутствовать функция exept -  может принимать различные значения в зависимости от того на какую ошибку мы проверяем. Эта конструкция так называемая защита от дурака.

Общий вид:

try:
 
  операторы
except():
 
  блок обработки исключений

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

\

Tell us about this  structure, ad  structure unit necessarily begins with try:
it must also attend a function exept - can take on different values depending on at what a mistake we check. This  structure is the so-called foolproof.

General appearance:

try:
    operators
except ():
    exception handling block


In the program I used two key TypeError exception handling and ValueError.
TypeError - check does not match the data type.
ValueError - check for an incorrect value.

Due to these keys I check in your program correctly entered input data - the price of candy, cookies and weight purchases.
In theory, if something is not right then introduced works display a warning about an invalid value. In my program it works, but not as I would like.

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

Решение задач на Python. Часть 2. / Solving problems in Python. Part 2

Всем привет, сегодня я расскажу о небольшой программе написанной мной на выходных, она представляет собой задачу найденную мной в интернете. Я придерживался задания и выполнил как было нужно, но после я пошел дальше и усовершенствовал код.
/
Hello everyone, today I will talk about a small program written by me on the weekends, it is a problem found in the Internet. I stuck to the task and performed as needed, but after I went ahead and improved code.

Изначальный вариант:

Пользователь вводит цены 1 килограмм конфет и 1 килограмм печенья. Найдите стоимость: а) одной покупки из 300 грамм конфет и 400 грамм печенья; б) трех покупок, каждая из 2 килограмм печенья и 1 килограмм 800 грамм конфет.
/
The original version:

The user enters the price of 1 kilogram of sweets and biscuits 1 kilogram. Find the value of: a) a purchase of 300 grams and 400 grams of sweets biscuits; b) Number three, each 2 pounds of biscuits and 1 kilo 800 grams of sweets.

a=float (input("цена 1 кг конфет: "))
b=float (input("цена 1 кг печенья: "))

print ("Стоимость 300 граммов конфет:",(a/1000)*300, "рубля")
print ("Стоимость 400 граммов печенья:",(a/1000)*400, "рубля")
print ("Стоимость трех покупок, каждая из 2 кг печенья и 1 кг 800 г конфет:",((b*2)+a+((a/1000)*800))*3, "рублей " )

Здесь мы используем тип данных float () - для использования чисел с плавающей точкой, за счет этого мы можем рассчитать цену продукта более точно.
Формулу расчета мы встраиваем прямо в вывод, для более короткой записи.
/
Here we use the data type float () - to use floating-point numbers, due to this we can calculate the price of the product more accurately.
Calculation formula we embed directly in the output for a shorter recording.

Измененный  вариант:
Amended version:


a=float (input("цена 1 кг конфет: "))
c=float (input("Сколько взвесить граммов конфет ?"))
b=float (input("цена 1 кг печенья: "))
d=float (input("Сколько взвесить граммов печенья ?"))

x=(a/1000)*c
y=(b/1000)*d
z=x+y

print ("Стоимость",c,"граммов печенья:",x,"рублей")
print ("Стоимость",d,"граммов печенья:",y,"рублей")
print ("Общая стоимость покупки:",z,"рублей")


В моем варианте той же задачи, я использую четыре переменных , две переменных (a,b) для ввода цены за один килограмм и две переменных (c,d) для ввода количества взвешиваемого товара.
В этой программе расчет делается не в поле вывода, а в отдельных переменных.
Вес покупки вводится в тысячах.
Программа будет обновлять и доделываться - планирую внедрить цикл if-else для защиты от ошибок ввода.
/
In my version of the same problem, I use four variables, the two variables (a, b) to enter the price per kilogram and two variables (c, d) to enter the number of the weighing product.
In this program, the calculation is not in the output, and in some variables.
Weight is expressed in thousands of purchase.
The program will update and finish - is planning to introduce a cycle if-else to protect against typing errors.