четверг, 19 марта 2015 г.

Калькулятор / Calculator

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

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

Первая функция под названием input_value - я ее создал для выбора действия, при вводе числа - выбирается действие с числами.
Вторая и третья функция под названием input_digit и input_digit2 - они созданы для ввода в по программу чисел над которыми производятся операции.

После функций следует блок непосредственных расчетов - техника выбора основывается на сравнивании значения введенного в первой функции с значением заданным в цикле if-elif-else.

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

/

Hello everyone, today I want to tell you about my kind of calculator, it does little action - this addition, subtraction, multiplication, division.
Developing further and I will add new computing activities.

Question of the day - this is how to optimize the code? Can I use my version of one function instead of three?
In the program I use an exception handler to check
TypeError - check does not match the data type.
ValueError - check for an incorrect value.

The first function called input_value - I created it to select actions when entering numbers - select action with numbers.
The second and third feature called input_digit and input_digit2 - they are made to enter in to the program numbers on which operations are performed.

After the function block should direct payments - selection technique is based on a comparison between the values ​​entered in the first function with the value specified in the loop if-elif-else.

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


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

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

value = input_value("number of action","message_error")


def input_digit(message3, message_error3):
    while True:
        try:
            digit= float(input(message3))
            return digit
        except (TypeError, ValueError):
            print(message_error3)

digit = input_digit("enter the first number","message_error3")


def input_digit2(message2, message_error2):
    while True:
        try:
            digit2 = int(input(message2))
            return digit2
        except (TypeError, ValueError):
            print(message_error2)

digit2 = input_digit2("Enter the second number","message_error2")


if value==1:
    addition = digit + digit2
    print (addition)
elif value==2:
    subtracting = digit - digit2
    print(subtracting)
elif value==3:
    multiplication = digit * digit2
    print(multiplication)
elif value==4:
    division = digit / digit2
    print (division)
else:
    print("fail")

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

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