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

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

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