HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Basic calculator program in Python

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
programcalculatorpythonbasic

Problem

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 = i

Solution

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.

Context

StackExchange Code Review Q#142851, answer score: 5

Revisions (0)

No revisions yet.