patternpythonMinor
Four-function calculator with roots and powers
Viewed 0 times
withrootsfourfunctionpowersandcalculator
Problem
I have some code for a calculator, and I was wondering what I could look at to make the code smaller, easier to read or better in any way. I'm particularly looking at my global variable
```
def Addition():
print('Addition: What are your numbers?')
a = float(input('First Number:'))
b = float(input('Second Number:'))
print('Your Answer is:', a + b)
def Subtraction():
print('Subtraction: What are your numbers?')
c = float(input('First Number:'))
d = float(input('Second Number:'))
print('Your Answer is:', c - d)
def Multiplication():
print('Multiplication: What are your numbers?')
e = float(input('First Number:'))
f = float(input('Second Number:'))
print('Your Answer is:', e * f)
def Division():
print('Division: What are your numbers?')
g = float(input('First Number:'))
h = float(input('Second Number:'))
print('Your Answer is:', g / h)
def Roots():
print('Roots: What do you want to Root?')
i = float(input('Number:'))
print('Roots: By what root?')
j = float(input('Number:'))
k = ( 1 / j )
print('Your Answer is:',i**k)
def Powers():
print('Powers: What number would you like to multiply by itself?')
l = float(input('Number:'))
print('Powers: How many times would you like to multiply by itself?')
m = float(input('Number:'))
print('Your Answer is:',l**m)
x = 'test'
def Question():
print('What would you like to do?')
x = input('(Add, Subtract, Divide, Multiply, Powers, Roots or Quit)')
if x.lower().startswith('a'):
x = 'test123'
print(Addition())
x = 'test'
elif x.lower().startswith('d'):
x = 'test123'
print(Division())
x = 'te
x. Is there any way to change the code to completely remove that? Someone mentioned a getTwoInputs() function, but with multiple different questions (powers() input and addition() input) I assume it would take up the same space.```
def Addition():
print('Addition: What are your numbers?')
a = float(input('First Number:'))
b = float(input('Second Number:'))
print('Your Answer is:', a + b)
def Subtraction():
print('Subtraction: What are your numbers?')
c = float(input('First Number:'))
d = float(input('Second Number:'))
print('Your Answer is:', c - d)
def Multiplication():
print('Multiplication: What are your numbers?')
e = float(input('First Number:'))
f = float(input('Second Number:'))
print('Your Answer is:', e * f)
def Division():
print('Division: What are your numbers?')
g = float(input('First Number:'))
h = float(input('Second Number:'))
print('Your Answer is:', g / h)
def Roots():
print('Roots: What do you want to Root?')
i = float(input('Number:'))
print('Roots: By what root?')
j = float(input('Number:'))
k = ( 1 / j )
print('Your Answer is:',i**k)
def Powers():
print('Powers: What number would you like to multiply by itself?')
l = float(input('Number:'))
print('Powers: How many times would you like to multiply by itself?')
m = float(input('Number:'))
print('Your Answer is:',l**m)
x = 'test'
def Question():
print('What would you like to do?')
x = input('(Add, Subtract, Divide, Multiply, Powers, Roots or Quit)')
if x.lower().startswith('a'):
x = 'test123'
print(Addition())
x = 'test'
elif x.lower().startswith('d'):
x = 'test123'
print(Division())
x = 'te
Solution
I am not sure it is very clear to you what your different functions are returning as you seem to be trying to print their return value even though they do not return anything special.
You do not need to change your variable names in each function without special reason.
The way you use your
Most of what happens in your function is (pretty much) the same from one to another. A good thing to do is to try to avoid repetition whenever you can and to abstract common behaviors. The quick and dirty way I've used to avoid such a repetition was to notice that you ask the user for 2 numbers anyway so it doesn't really matter which operator we will use them for. My minimalist solution stores things in a dictionary (you could improve the content of the dictionary if you wanted to have more things changing from one operator to another such as user prompts).
You do not need to change your variable names in each function without special reason.
a and b are decent names in your case, you don't need to use c and d later and then e and f as there is no way to get confused anyway.The way you use your
x variable is pretty cryptic to me. I guess this is just some testing/debugging but it would help if you could submit a clean version of your code for reviewing.Most of what happens in your function is (pretty much) the same from one to another. A good thing to do is to try to avoid repetition whenever you can and to abstract common behaviors. The quick and dirty way I've used to avoid such a repetition was to notice that you ask the user for 2 numbers anyway so it doesn't really matter which operator we will use them for. My minimalist solution stores things in a dictionary (you could improve the content of the dictionary if you wanted to have more things changing from one operator to another such as user prompts).
#!/usr/bin/python
import operator
operations={
'a':('Addition', operator.add),
's':('Substraction', operator.sub),
'm':('Multiplication',operator.mul),
'd':('Division', operator.truediv),
'p':('Power', operator.pow),
'r':('Root', lambda x, y:x**(1/y)),
}
while True:
# TODO : Next line could be generated from the list if it keeps growing
x = input('(Add, Subtract, Divide, Multiply, Powers, Roots or Quit)').lower()
if x in operations:
operation_name,operator=operations[x]
print(operation_name)
a = float(input('First Number:'))
b = float(input('Second Number:'))
print("Your answer is ",operator(a,b))
elif x.startswith('q'):
break
else:
print("Please type the first letter of what you want to do.")Code Snippets
#!/usr/bin/python
import operator
operations={
'a':('Addition', operator.add),
's':('Substraction', operator.sub),
'm':('Multiplication',operator.mul),
'd':('Division', operator.truediv),
'p':('Power', operator.pow),
'r':('Root', lambda x, y:x**(1/y)),
}
while True:
# TODO : Next line could be generated from the list if it keeps growing
x = input('(Add, Subtract, Divide, Multiply, Powers, Roots or Quit)').lower()
if x in operations:
operation_name,operator=operations[x]
print(operation_name)
a = float(input('First Number:'))
b = float(input('Second Number:'))
print("Your answer is ",operator(a,b))
elif x.startswith('q'):
break
else:
print("Please type the first letter of what you want to do.")Context
StackExchange Code Review Q#25701, answer score: 5
Revisions (0)
No revisions yet.