@HackerMaster05

Как улучшить код?

Вчера начал изучать Python. Оцените пожалуйста код:
import math
from operator import *
 
#Functions for the calculating
def calc():
    select = input("Select an operator: + - * / ** √\n")
    operators = ["+", "-", "*", "/", "**"]
    try:
        if select == "√":
            root = float(input("Enter a number..."))
            print("√", root,"=", math.sqrt(root))
        elif select in operators:
            num1 = float(input("Enter the first number...\n"))
            num2 = float(input("Enter the second number...\n"))
            if select == "+":
                print(num1, "+",num2,"=", add(num1, num2))
            elif select == "-":
                print(num1, "-",num2,"=", sub(num1, num2))
            elif select == "*":
                print(num1, "*",num2,"=",  mul(num1, num2))
            elif select == "/":
                print(num1, "/",num2,"=", div(num1, num2))
            elif select == "**":
                print(num1, "**",num2,"=", pow(num1, num2))
            else:
                print("Error, invalid input")
    except:
        print("Error, you need to enter a number")
 
#The main function which use a while loop
def main():
    i = 0
    while True:
        if i == 0:
            calc()
        #print('\nCalculation finished. Do another? (Y/N)')
        selector = input("Calculation finished. Do another? (Y/N)\n")
        if selector.lower() == 'n':
            break
        elif selector.lower() == 'y':
            calc()
        i = 1
 
#About the script, here I use the main function
print("This is a simple calculator on python")
main()

Буду благодарен за любую критику!
  • Вопрос задан
  • 166 просмотров
Решения вопроса 2
@kolomiec_artiom
Ну, для того, чтобы визуально уменьшить код - я бы использовал вместо конструкции "if - else" словарь
Ответ написан
fox_12
@fox_12 Куратор тега Python
Расставляю биты, управляю заряженными частицами
Как улучшить код?

К примеру так:
import math
import operator

def calc():
    op = input("Select an operator: + - * / ** √\n")
    
    if op in ['√']:
        num = float(input('Enter a number: '))
        res = f'√{num} = {math.sqrt(num)}'
    else:
        num1 = float(input("Enter the first number...\n"))
        num2 = float(input("Enter the second number...\n"))
        res = {
           '+': f'{num1} + {num2} = {operator.add(num1, num2)}',
           '-': f'{num1} - {num2} = {operator.sub(num1, num2)}',
           '*': f'{num1} * {num2} = {operator.mul(num1, num2)}',
           '/': f'{num1} / {num2} = {operator.truediv(num1, num2)}',
           '**': f'{num1} ** {num2} = {operator.pow(num1, num2)}',
        }.get(op, 'Unknown operation')
    print(res)

if __name__ == '__main__':
    print("This is a simple calculator on python")
    while True:
        calc()
        if input("Calculation finished. Do another? (Y/N)\n").lower() != 'y':
            break

А можно и мой вариант улучшить.
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы