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

суббота, 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.