Skip to main content
edited tags
Link
200_success
  • 144.2k
  • 22
  • 188
  • 473
Source Link
sg7610
  • 368
  • 3
  • 12

A simple python3 calculator

Made a very simple calculator in Python. The program has the following features:

  1. All the basic operators can be used. '+', '-', '*', '**', '/', and '//'.
  2. The user can start the program again.
  3. The previous output is available for the user to use again.
def start(out='temp'):
    # Get the input from the user and pass all the values to verify.
    # Explicit test is used because the output can be zero.
    if out != 'temp':
        x = out
        print('\nFirst number: ', x)
    else:
        x = input('\nFirst number: ')
    op = input('Operator: ')
    y = input('Second number: ')
    verify(x, op, y)

def verify(x, op, y):
    # Check if the operator and the numbers entered are valid.
    # If any input is invalid call start and get input again.
    # If inputs are valid pass all the values to calc.
    ops = ['+', '-', '*', '**', '/', '//']
    if op in ops:
        try:
            x, y = int(x), int(y)
        except ValueError:
            print('Numbers are not valid.\n')
            start()
        else:
            calc(x, op, y)            
    else:
        print('Please enter a valid operator.\n')
        start()

def calc(x, op, y):
    # Use eval to calculate the output and pass the output to 
    # restart.
    out = eval(f'x {op} y')
    print('Output:', out)
    restart(out)

def restart(out):
    # User can start the process again. The previous output can be used as
    # the first number.
    re = input('Start again? (y/n): ')
    if re == 'y':
        use_out = input(
            'Use the previous output as the first number? (y/n): ')
        if use_out == 'y':
            start(out=out)
        else:
            start()
    else:
        print('Calc is now closed.')

start()

Here's a sample output.

First number: 5
Operator: *
Second number: 9
Output: 45
Start again? (y/n): y
Use the previous output as the first number? (y/n): y

First number:  45
Operator: //
Second number: 2
Output: 22
Start again? (y/n): n
Calc is now closed.

I am looking for ways to make the code more readable, minimize redundancy, improving the overall design, etc. Any help would be appreciated!