elif choice == '2':
instructions()
main()
Ummm, that's probably not exactly what you want.
Python lacks a goto
statement, so the usual idiom would be to wrap the whole thing in some sort of while
loop, perhaps while True
.
Consider an input sequence of "2 2 2 2 2", or "z z z z z".
You'll wind up pushing main
onto the call stack again, and again, and again....
Your locals never go out of scope, so their ref count never decrements and they won't be deallocated and tidied up.
tl;dr: leaking stack frames is Bad, don't do it.
print("Last Result: "+str(result))
Usual idiom would be print('Last Result:', result)
, but no harm done.
num1 = int(input("First Number: "))
The requirements seemed pretty clear about "...must work with decimal numbers."
You chose to invoke int()
rather than float()
.
if result != 0:
num1 = result
I can't imagine how that corresponds to The Right Thing.
If you want a sentinel, None
would be much better than 0
,
just consider a sequence like 2 + 1 = - 3 =
(which yields zero).
Perhaps there's a reason for assigning the accumulator to num1
, but I'm not seeing it.
It appears you have discarded the user input.
operator = input("Opertaor: ").lower()
Typo.
calculator()
Same criticism as above. Python lacks goto
, and you're leaking stack frames here.
if operator == "sqrt":
result = (sqrt(num1))
print("Result: "+str(result))
continue
It is apparent that I'm not understanding why you are using the result
accumulator versus the num1
user input.
On most calculators, repeated clicking of the √ key would yield repeated assignment of result = sqrt(result)
.
I'm a little concerned about num1
versus result
confusion.
if operator=="esc":
main()
Same remark about leaking stack frames.
A return
statement would be usual, here.
if operator.isdigit():
This seems a bit restrictive. Better to unconditionally raise an "unrecognized operator" error.
num2 = int(input("Second Number: "))
Same criticism as above, the "decimal" instructions are pretty clear about calling float()
.
result = (add(num1,num2))
All four of these assignments seem pretty weird,
as for a typical calculator we'd be accumulating result = add(result, num2)
.
This is a consequence of the num1
assignment above.
Also, please discard the (
extraneous parentheses)
.
def sqrt(num1):
return (num1**(1/2.0))
This works fine, but do consider the usual idiom of simply calling math.sqrt()
.