-1
\$\begingroup\$

I am really new to Python and programming in general and I am trying to improve doing some projects like this one. I would like to know how I can improve this the right way.

 """A simple calculator """


def additions():
    print("ADDITION:")
    num1 = input("Give me your first number: ")
    num2 = input("Give me a second number: ")
    try:
        result = float(num1) + float(num2)
        print(result)
    except ValueError:
        print("INVALID")


def subtractions():
    print("SUBTRACTION:")
    num1 = input("Give me your first number: ")
    num2 = input("Give me a second number: ")
    try:
        result = float(num1) + float(num2)
        print(result)
    except ValueError:
        print("INVALID")


def divisions():
    print("DIVISION:")
    num1 = input("Give me your first number: ")
    num2 = input("Give me a second number: ")
    try:
        result = float(num1) + float(num2)
        print(result)
    except ValueError:
        print("INVALID")


def multiplications():
    print("MULTIPLICATION:")
    num1 = input("Give me your first number: ")
    num2 = input("Give me a second number: ")
    try:
        result = float(num1) + float(num2)
        print(result)
    except ValueError:
        print("INVALID")


print("Hello to Simple Calculator ver.0.0003.")
print("Type:\n 1. for Addition.\n 2. for Subtraction .\n 3. for Multiplication.\n 4. for Division. \n 0. to EXIT.")

while True:
    try:
        user_input = int(input("What operation do you need? "))
    except ValueError:
        print("INVALID!!!")
        continue
    if user_input == 1:
        additions()
    elif user_input == 2:
        subtractions()
    elif user_input == 3:
        multiplications()
    elif user_input == 4:
        divisions()
    elif user_input == 0:
        break
\$\endgroup\$
  • 1
    \$\begingroup\$ Double check your operations. Currently they're all addition. \$\endgroup\$ – Reinderien Nov 22 '18 at 0:54
1
\$\begingroup\$

For a beginner this is not bad at all. Consider factoring out repeated code into its own function, particularly the code that reads two input numbers and converts them to floats. In that function you could also include the printing of the operation title. Finally, consider putting your globally scoped code into a main function.

The application can be even more abbreviated if you use the operator library and some simple tuple lookups:

#!/usr/bin/env python3

from operator import add, sub, mul, truediv

'''A simple calculator '''


def main():
    ops = (('Addition', add),
           ('Subtraction', sub),
           ('Multiplication', mul),
           ('Division', truediv))
    print('Hello to Simple Calculator ver.0.0003.')
    print('Type:')
    print('\n'.join(' %d. for %s' % (i+1, name)
                    for i, (name, op) in enumerate(ops)))
    print(' 0. to exit')

    while True:
        try:
            user_input = int(input('What operation do you need? '))
        except ValueError:
            print('Invalid input.')
            continue
        if user_input == 0:
            break
        elif 1 <= user_input <= 4:
            title, op = ops[user_input - 1]
            print('%s:' % title)
            try:
                num1 = float(input('Give me your first number: '))
                num2 = float(input('Give me a second number: '))
                print(op(num1, num2))
            except ValueError:
                print('Invalid input.')
        else:
            print('Invalid input.')


if __name__ == '__main__':
    main()

You don't even need your operations to be separated into functions.

\$\endgroup\$
  • \$\begingroup\$ This was really helpful thank you very much . \$\endgroup\$ – skyn37 Nov 22 '18 at 11:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.