5
\$\begingroup\$

I was writing a basic calculator program to practice my skills at python. I'm a beginner at Python and was wondering if there is a way to simplify this code of mine? It seems a little bit too long and messy in some sort of way. Again, I'm still a beginner so I don't know all the tricks in the book!

import math
import time

def add(x,y):
  return x + y

def subtract(x,y):
  return x - y

def divide(x,y):
  return x / y

def multiply(x,y):
  return x * y

def sqrt(x):
  if math.sqrt(x) * math.sqrt(x):
     return False
  else:
     return math.sqrt(x)


def power(x,y):
  return math.pow(x,y)

def repeat():
  print('Would you like to perform another calculation? y/n')
  rep = input('')
  if rep.lower() == 'y':
     time.sleep(0.5)
     main()
  elif rep.lower() == 'n':
     print('Goodbye!')
     time.sleep(1)
     exit()
  else:
     print('Please enter y/n.')
     time.sleep(1)
     repeat()

def numCheck(x):
  try:
     int(x)
  except ValueError:
     print("Please enter a valid number.")
     print('')
     time.sleep(1)
     main()


def choiceCheck(y, z):
   for x in y:
       if x == z:
           return True
           break
       else:
           pass


def main():
  choices = ['1', '2', '3', '4']
  print('Choose your operation: ')
  print('1. Add')
  print('2. Subtract')
  print('3. Divide')
  print('4. Multiply')
  print('5. Square Root')
  print('6. Exponent')
  print('1/2/3/4/5/6')
  choice = input('')
  if choice == '5':
     print('Please choose the number you would like to square root.')
     rt = input('')
     numCheck(rt)
     rt = int(rt)
     rts = sqrt(rt)
     if rts == False:
        print('%d is an irrational number.' % (rt))
     else:
        print('The square root of %d is %d' % (rt, rts))
        repeat() 
  elif choice == '6':       
     print('Choose the number you would like to raise to a power: ')
     base = input('')
     numCheck(base)
     base = int(base)
     print('')
     print('Now please choose the indice: ')
     ind = input('')
     numCheck(ind)
     ind = int(ind)
     time.sleep(1)
     print('%d to the power of %d is %d' % (base, ind, power(base,ind)))
     repeat()
  elif choiceCheck(choices, choice) != True: 
     print('Please choose a valid number.')
     print('')
     time.sleep(1)
     main()
  a = input('Please choose your first number: ')
  numCheck(a)
  a = int(a)
  print('')
  b = input('Please choose your second number: ')
  numCheck(b)
  b = int(b)
  if choice == '1':
     print('%d + %d = %d' % (a, b, add(a,b)))
  elif choice == '2':
     print('%d - %d = %d' % (a, b, subtract(a,b)))
  elif choice == '3':
     print('%r / %r = %r' % (a, b, divide(a,b)))
  elif choice == '4':
     print('%d * %d = %d' % (a, b, multiply(a,b)))
  else:
     print('Please choose a valid number')
     print('')
     time.sleep(1)
     main()
  repeat()


main()

All help is appreciated!

\$\endgroup\$
  • 2
    \$\begingroup\$ I don't get if math.sqrt(x) * math.sqrt(x): return False. What is it for? \$\endgroup\$ – Mahmood Muhammad Nageeb Sep 29 '16 at 21:36
  • \$\begingroup\$ should probably be if x<0 return False. And there's a lot of useless recursion on main. \$\endgroup\$ – Jean-François Fabre Sep 29 '16 at 21:45
5
\$\begingroup\$

This being Python, where indentation is significant, it is important to consistently follow the convention of four spaces per level.

You shouldn't format the square root as %d, since the result is rarely an integer.

There are several recommendations that I could make about organizing this code, but the single most important point is that functions should not be treated as goto labels. If you need a loop, then write a loop using while or for. Don't have main call main(). Don't have repeat call main(). Don't have repeat call repeat(). Otherwise, you end up with spaghetti code.

\$\endgroup\$

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.