Calculator final project in Python The Next CEO of Stack OverflowPython calculator scriptSimple calculator for an interviewSimple python calculatorPython calculatorPython 3 - CalculatorPython BMI CalculatorSemi-simple calculatortkinter calculator college projectBasic calculator in PythonSimple Python calculator 5

Small nick on power cord from an electric alarm clock, and copper wiring exposed but intact

How can a day be of 24 hours?

How can the PCs determine if an item is a phylactery?

Direct Implications Between USA and UK in Event of No-Deal Brexit

Which acid/base does a strong base/acid react when added to a buffer solution?

Can Sri Krishna be called 'a person'?

Why did the Drakh emissary look so blurred in S04:E11 "Lines of Communication"?

Are British MPs missing the point, with these 'Indicative Votes'?

What steps are necessary to read a Modern SSD in Medieval Europe?

What does this strange code stamp on my passport mean?

Gauss' Posthumous Publications?

How to show a landlord what we have in savings?

Why was Sir Cadogan fired?

"Eavesdropping" vs "Listen in on"

Is it reasonable to ask other researchers to send me their previous grant applications?

Is there a rule of thumb for determining the amount one should accept for of a settlement offer?

pgfplots: How to draw a tangent graph below two others?

How seriously should I take size and weight limits of hand luggage?

Is it possible to create a QR code using text?

Could you use a laser beam as a modulated carrier wave for radio signal?

What is the difference between 'contrib' and 'non-free' packages repositories?

MT "will strike" & LXX "will watch carefully" (Gen 3:15)?

Is it correct to say moon starry nights?

Calculate the Mean mean of two numbers



Calculator final project in Python



The Next CEO of Stack OverflowPython calculator scriptSimple calculator for an interviewSimple python calculatorPython calculatorPython 3 - CalculatorPython BMI CalculatorSemi-simple calculatortkinter calculator college projectBasic calculator in PythonSimple Python calculator 5










5












$begingroup$


In my final project for my Python course, I am required to create a calculator program. I really need someone to look over my code and tell me if I have met all the requirements for this project.



Here are the requirements:




For the final project, you are to write a calculator program in Python
with the following characteristics:



  • It must be at least 50 lines of code excluding comments

  • It must have the following functions:+,-,*,/, SQRT, and work with decimal numbers.

  • It must be all text, no high resolution graphics

  • It must automatically copy the result to the operating system clipboard

  • It must work as a functional calculator (calculations can be entered over and over)

Please submit the source code only (.py), no object code (I will
compile on receipt)



NOTE:



  1. This assignment is graded on a pass/fail basis; there is no partial credit or resubmissions. Be sure you understand ALL of the
    requirements.


  2. Solutions that require the user install any software will NOT be accepted (in case you are not sure, this means NO Pyperclip.)


WARNING: All submissions will be checked for plagiarism using
SafeAssign or other plagiarism checker.




I completed the project, but because this is a pass/fail project I want to be 200% sure I have met every requirement. I am also open to any other feedback that would sharpen my Python skills.



Menu



def main():
#Menu
print("=======================")
print("Welcome to Calculator")
print("By: Tyler Harris")
print("=======================")
print("Menu: ")
print("[1] Calculator")
print("[2] Instructions")
print("[3] Exit")
print("=======================")
choice = input("Please select an option: ")
if choice == '1':
calculator()
elif choice == '2':
instructions()
main()
elif choice == '3':
print("Thank you for using Calculator.")
else:
print("Not an option, try again:")
main()


Calculator



def calculator():
result=0 #Resets calulator.
try:
while True:
print("Last Result: "+str(result))

#Number 1 input.
if result == 0:
num1= int(input("First Number: "))
if result != 0:
num1=result

#Operator input.
#Checks for input of special operators 'c', 'sqrt', and 'esc'.
operator=input("Opertaor: ").lower()
if operator == "c":
print("Calculator cleared")
calculator()
if operator=="sqrt":
result=(sqrt(num1))
print("Result: "+str(result))
continue
if operator=="esc":
main()
if operator.isdigit(): #Throw error if operator is a number.
raise Exception()

#Number 2 input.
num2= int(input("Second Number: "))
#Operator calls.
if operator=="+":
result=(add(num1,num2))
elif operator=="-":
result=(sub(num1,num2))
elif operator=="*":
result=(mult(num1,num2))
elif operator=="/":
result=(div(num1,num2))


#Copy result to System's clipboard and display the result.
copy2clip(str(result))
print("=======================")
print("Result: "+str(result))
print("copied to clipboard")
print("=======================")

#Catch any errors and reset calculator
except Exception:
print("=======================")
print("Error Please try again.")
calculator()
else:
calculator()


Operators



def add(num1,num2):
return num1 + num2
def sub(num1,num2):
return num1 - num2
def mult(num1,num2):
return num1 * num2
def div(num1,num2):
return num1 / num2
def sqrt(num1):
return (num1**(1/2.0))


Instructions



def instructions():
print("=======================")
print(format('Calculator','^25s'))
print("=======================")
print("Available operators")
print("+: Addition")
print("-: Subtraction")
print("*: Multiplication")
print("/: Division")
print("sqrt: Square Root")
print("c: Clear Calculator")
print("esc: Exit Calculator")
print("=======================")

def copy2clip(txt):
cmd='echo '+txt.strip()+'|clip'
return subprocess.check_call(cmd, shell=True)

if __name__=='__main__':
main()









share|improve this question











$endgroup$



migrated from stackoverflow.com yesterday


This question came from our site for professional and enthusiast programmers.













  • 1




    $begingroup$
    I would suggest you don't use raise Exception, instead provide a bit more info i.e. raise ValueError('Operator must be a digit').
    $endgroup$
    – David Waterworth
    yesterday











  • $begingroup$
    I'm afraid I don't have time for a full review, but one thing I did pick up on and wants checking is the requirement to "work with decimal numbers." It may be worth clarifying whether it's fine to use floating point numbers, or whether you're specifically expected to use the decimal library: docs.python.org/3.7/library/decimal.html
    $endgroup$
    – Josiah
    yesterday















5












$begingroup$


In my final project for my Python course, I am required to create a calculator program. I really need someone to look over my code and tell me if I have met all the requirements for this project.



Here are the requirements:




For the final project, you are to write a calculator program in Python
with the following characteristics:



  • It must be at least 50 lines of code excluding comments

  • It must have the following functions:+,-,*,/, SQRT, and work with decimal numbers.

  • It must be all text, no high resolution graphics

  • It must automatically copy the result to the operating system clipboard

  • It must work as a functional calculator (calculations can be entered over and over)

Please submit the source code only (.py), no object code (I will
compile on receipt)



NOTE:



  1. This assignment is graded on a pass/fail basis; there is no partial credit or resubmissions. Be sure you understand ALL of the
    requirements.


  2. Solutions that require the user install any software will NOT be accepted (in case you are not sure, this means NO Pyperclip.)


WARNING: All submissions will be checked for plagiarism using
SafeAssign or other plagiarism checker.




I completed the project, but because this is a pass/fail project I want to be 200% sure I have met every requirement. I am also open to any other feedback that would sharpen my Python skills.



Menu



def main():
#Menu
print("=======================")
print("Welcome to Calculator")
print("By: Tyler Harris")
print("=======================")
print("Menu: ")
print("[1] Calculator")
print("[2] Instructions")
print("[3] Exit")
print("=======================")
choice = input("Please select an option: ")
if choice == '1':
calculator()
elif choice == '2':
instructions()
main()
elif choice == '3':
print("Thank you for using Calculator.")
else:
print("Not an option, try again:")
main()


Calculator



def calculator():
result=0 #Resets calulator.
try:
while True:
print("Last Result: "+str(result))

#Number 1 input.
if result == 0:
num1= int(input("First Number: "))
if result != 0:
num1=result

#Operator input.
#Checks for input of special operators 'c', 'sqrt', and 'esc'.
operator=input("Opertaor: ").lower()
if operator == "c":
print("Calculator cleared")
calculator()
if operator=="sqrt":
result=(sqrt(num1))
print("Result: "+str(result))
continue
if operator=="esc":
main()
if operator.isdigit(): #Throw error if operator is a number.
raise Exception()

#Number 2 input.
num2= int(input("Second Number: "))
#Operator calls.
if operator=="+":
result=(add(num1,num2))
elif operator=="-":
result=(sub(num1,num2))
elif operator=="*":
result=(mult(num1,num2))
elif operator=="/":
result=(div(num1,num2))


#Copy result to System's clipboard and display the result.
copy2clip(str(result))
print("=======================")
print("Result: "+str(result))
print("copied to clipboard")
print("=======================")

#Catch any errors and reset calculator
except Exception:
print("=======================")
print("Error Please try again.")
calculator()
else:
calculator()


Operators



def add(num1,num2):
return num1 + num2
def sub(num1,num2):
return num1 - num2
def mult(num1,num2):
return num1 * num2
def div(num1,num2):
return num1 / num2
def sqrt(num1):
return (num1**(1/2.0))


Instructions



def instructions():
print("=======================")
print(format('Calculator','^25s'))
print("=======================")
print("Available operators")
print("+: Addition")
print("-: Subtraction")
print("*: Multiplication")
print("/: Division")
print("sqrt: Square Root")
print("c: Clear Calculator")
print("esc: Exit Calculator")
print("=======================")

def copy2clip(txt):
cmd='echo '+txt.strip()+'|clip'
return subprocess.check_call(cmd, shell=True)

if __name__=='__main__':
main()









share|improve this question











$endgroup$



migrated from stackoverflow.com yesterday


This question came from our site for professional and enthusiast programmers.













  • 1




    $begingroup$
    I would suggest you don't use raise Exception, instead provide a bit more info i.e. raise ValueError('Operator must be a digit').
    $endgroup$
    – David Waterworth
    yesterday











  • $begingroup$
    I'm afraid I don't have time for a full review, but one thing I did pick up on and wants checking is the requirement to "work with decimal numbers." It may be worth clarifying whether it's fine to use floating point numbers, or whether you're specifically expected to use the decimal library: docs.python.org/3.7/library/decimal.html
    $endgroup$
    – Josiah
    yesterday













5












5








5





$begingroup$


In my final project for my Python course, I am required to create a calculator program. I really need someone to look over my code and tell me if I have met all the requirements for this project.



Here are the requirements:




For the final project, you are to write a calculator program in Python
with the following characteristics:



  • It must be at least 50 lines of code excluding comments

  • It must have the following functions:+,-,*,/, SQRT, and work with decimal numbers.

  • It must be all text, no high resolution graphics

  • It must automatically copy the result to the operating system clipboard

  • It must work as a functional calculator (calculations can be entered over and over)

Please submit the source code only (.py), no object code (I will
compile on receipt)



NOTE:



  1. This assignment is graded on a pass/fail basis; there is no partial credit or resubmissions. Be sure you understand ALL of the
    requirements.


  2. Solutions that require the user install any software will NOT be accepted (in case you are not sure, this means NO Pyperclip.)


WARNING: All submissions will be checked for plagiarism using
SafeAssign or other plagiarism checker.




I completed the project, but because this is a pass/fail project I want to be 200% sure I have met every requirement. I am also open to any other feedback that would sharpen my Python skills.



Menu



def main():
#Menu
print("=======================")
print("Welcome to Calculator")
print("By: Tyler Harris")
print("=======================")
print("Menu: ")
print("[1] Calculator")
print("[2] Instructions")
print("[3] Exit")
print("=======================")
choice = input("Please select an option: ")
if choice == '1':
calculator()
elif choice == '2':
instructions()
main()
elif choice == '3':
print("Thank you for using Calculator.")
else:
print("Not an option, try again:")
main()


Calculator



def calculator():
result=0 #Resets calulator.
try:
while True:
print("Last Result: "+str(result))

#Number 1 input.
if result == 0:
num1= int(input("First Number: "))
if result != 0:
num1=result

#Operator input.
#Checks for input of special operators 'c', 'sqrt', and 'esc'.
operator=input("Opertaor: ").lower()
if operator == "c":
print("Calculator cleared")
calculator()
if operator=="sqrt":
result=(sqrt(num1))
print("Result: "+str(result))
continue
if operator=="esc":
main()
if operator.isdigit(): #Throw error if operator is a number.
raise Exception()

#Number 2 input.
num2= int(input("Second Number: "))
#Operator calls.
if operator=="+":
result=(add(num1,num2))
elif operator=="-":
result=(sub(num1,num2))
elif operator=="*":
result=(mult(num1,num2))
elif operator=="/":
result=(div(num1,num2))


#Copy result to System's clipboard and display the result.
copy2clip(str(result))
print("=======================")
print("Result: "+str(result))
print("copied to clipboard")
print("=======================")

#Catch any errors and reset calculator
except Exception:
print("=======================")
print("Error Please try again.")
calculator()
else:
calculator()


Operators



def add(num1,num2):
return num1 + num2
def sub(num1,num2):
return num1 - num2
def mult(num1,num2):
return num1 * num2
def div(num1,num2):
return num1 / num2
def sqrt(num1):
return (num1**(1/2.0))


Instructions



def instructions():
print("=======================")
print(format('Calculator','^25s'))
print("=======================")
print("Available operators")
print("+: Addition")
print("-: Subtraction")
print("*: Multiplication")
print("/: Division")
print("sqrt: Square Root")
print("c: Clear Calculator")
print("esc: Exit Calculator")
print("=======================")

def copy2clip(txt):
cmd='echo '+txt.strip()+'|clip'
return subprocess.check_call(cmd, shell=True)

if __name__=='__main__':
main()









share|improve this question











$endgroup$




In my final project for my Python course, I am required to create a calculator program. I really need someone to look over my code and tell me if I have met all the requirements for this project.



Here are the requirements:




For the final project, you are to write a calculator program in Python
with the following characteristics:



  • It must be at least 50 lines of code excluding comments

  • It must have the following functions:+,-,*,/, SQRT, and work with decimal numbers.

  • It must be all text, no high resolution graphics

  • It must automatically copy the result to the operating system clipboard

  • It must work as a functional calculator (calculations can be entered over and over)

Please submit the source code only (.py), no object code (I will
compile on receipt)



NOTE:



  1. This assignment is graded on a pass/fail basis; there is no partial credit or resubmissions. Be sure you understand ALL of the
    requirements.


  2. Solutions that require the user install any software will NOT be accepted (in case you are not sure, this means NO Pyperclip.)


WARNING: All submissions will be checked for plagiarism using
SafeAssign or other plagiarism checker.




I completed the project, but because this is a pass/fail project I want to be 200% sure I have met every requirement. I am also open to any other feedback that would sharpen my Python skills.



Menu



def main():
#Menu
print("=======================")
print("Welcome to Calculator")
print("By: Tyler Harris")
print("=======================")
print("Menu: ")
print("[1] Calculator")
print("[2] Instructions")
print("[3] Exit")
print("=======================")
choice = input("Please select an option: ")
if choice == '1':
calculator()
elif choice == '2':
instructions()
main()
elif choice == '3':
print("Thank you for using Calculator.")
else:
print("Not an option, try again:")
main()


Calculator



def calculator():
result=0 #Resets calulator.
try:
while True:
print("Last Result: "+str(result))

#Number 1 input.
if result == 0:
num1= int(input("First Number: "))
if result != 0:
num1=result

#Operator input.
#Checks for input of special operators 'c', 'sqrt', and 'esc'.
operator=input("Opertaor: ").lower()
if operator == "c":
print("Calculator cleared")
calculator()
if operator=="sqrt":
result=(sqrt(num1))
print("Result: "+str(result))
continue
if operator=="esc":
main()
if operator.isdigit(): #Throw error if operator is a number.
raise Exception()

#Number 2 input.
num2= int(input("Second Number: "))
#Operator calls.
if operator=="+":
result=(add(num1,num2))
elif operator=="-":
result=(sub(num1,num2))
elif operator=="*":
result=(mult(num1,num2))
elif operator=="/":
result=(div(num1,num2))


#Copy result to System's clipboard and display the result.
copy2clip(str(result))
print("=======================")
print("Result: "+str(result))
print("copied to clipboard")
print("=======================")

#Catch any errors and reset calculator
except Exception:
print("=======================")
print("Error Please try again.")
calculator()
else:
calculator()


Operators



def add(num1,num2):
return num1 + num2
def sub(num1,num2):
return num1 - num2
def mult(num1,num2):
return num1 * num2
def div(num1,num2):
return num1 / num2
def sqrt(num1):
return (num1**(1/2.0))


Instructions



def instructions():
print("=======================")
print(format('Calculator','^25s'))
print("=======================")
print("Available operators")
print("+: Addition")
print("-: Subtraction")
print("*: Multiplication")
print("/: Division")
print("sqrt: Square Root")
print("c: Clear Calculator")
print("esc: Exit Calculator")
print("=======================")

def copy2clip(txt):
cmd='echo '+txt.strip()+'|clip'
return subprocess.check_call(cmd, shell=True)

if __name__=='__main__':
main()






python python-3.x homework calculator






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited yesterday









200_success

131k17156420




131k17156420










asked 2 days ago







user3590710











migrated from stackoverflow.com yesterday


This question came from our site for professional and enthusiast programmers.









migrated from stackoverflow.com yesterday


This question came from our site for professional and enthusiast programmers.









  • 1




    $begingroup$
    I would suggest you don't use raise Exception, instead provide a bit more info i.e. raise ValueError('Operator must be a digit').
    $endgroup$
    – David Waterworth
    yesterday











  • $begingroup$
    I'm afraid I don't have time for a full review, but one thing I did pick up on and wants checking is the requirement to "work with decimal numbers." It may be worth clarifying whether it's fine to use floating point numbers, or whether you're specifically expected to use the decimal library: docs.python.org/3.7/library/decimal.html
    $endgroup$
    – Josiah
    yesterday












  • 1




    $begingroup$
    I would suggest you don't use raise Exception, instead provide a bit more info i.e. raise ValueError('Operator must be a digit').
    $endgroup$
    – David Waterworth
    yesterday











  • $begingroup$
    I'm afraid I don't have time for a full review, but one thing I did pick up on and wants checking is the requirement to "work with decimal numbers." It may be worth clarifying whether it's fine to use floating point numbers, or whether you're specifically expected to use the decimal library: docs.python.org/3.7/library/decimal.html
    $endgroup$
    – Josiah
    yesterday







1




1




$begingroup$
I would suggest you don't use raise Exception, instead provide a bit more info i.e. raise ValueError('Operator must be a digit').
$endgroup$
– David Waterworth
yesterday





$begingroup$
I would suggest you don't use raise Exception, instead provide a bit more info i.e. raise ValueError('Operator must be a digit').
$endgroup$
– David Waterworth
yesterday













$begingroup$
I'm afraid I don't have time for a full review, but one thing I did pick up on and wants checking is the requirement to "work with decimal numbers." It may be worth clarifying whether it's fine to use floating point numbers, or whether you're specifically expected to use the decimal library: docs.python.org/3.7/library/decimal.html
$endgroup$
– Josiah
yesterday




$begingroup$
I'm afraid I don't have time for a full review, but one thing I did pick up on and wants checking is the requirement to "work with decimal numbers." It may be worth clarifying whether it's fine to use floating point numbers, or whether you're specifically expected to use the decimal library: docs.python.org/3.7/library/decimal.html
$endgroup$
– Josiah
yesterday










2 Answers
2






active

oldest

votes


















7












$begingroup$

You are using function calls as if they were goto labels. That is a huge sin: it makes your program spaghetti code. If you want a loop, then write a loop. For example, main() should look like:



def main():
while True:
#Menu
print("=======================")
print("Welcome to Calculator")
print("By: Tyler Harris")
print("=======================")
print("Menu: ")
print("[1] Calculator")
print("[2] Instructions")
print("[3] Exit")
print("=======================")
choice = input("Please select an option: ")
if choice == '1':
calculator()
elif choice == '2':
instructions()
elif choice == '3':
print("Thank you for using Calculator.")
break
else:
print("Not an option, try again:")





share|improve this answer









$endgroup$




















    6












    $begingroup$

     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().






    share|improve this answer











    $endgroup$








    • 1




      $begingroup$
      Just to elaborate on the first point of why it is bad to keep calling main() - basically each time you call a method, you are 'entering' that method. But you never exit the method - you just keep going deeper into the wormhole with each main() call. As JH is saying, each time you call a method you are putting more data onto the stack, but since the methods never are allowed to exit, the data is never freed, which eventually means you run out of space and the application will stop working.
      $endgroup$
      – fabspro
      yesterday











    Your Answer





    StackExchange.ifUsing("editor", function ()
    return StackExchange.using("mathjaxEditing", function ()
    StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
    StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
    );
    );
    , "mathjax-editing");

    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "196"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f216557%2fcalculator-final-project-in-python%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown
























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    7












    $begingroup$

    You are using function calls as if they were goto labels. That is a huge sin: it makes your program spaghetti code. If you want a loop, then write a loop. For example, main() should look like:



    def main():
    while True:
    #Menu
    print("=======================")
    print("Welcome to Calculator")
    print("By: Tyler Harris")
    print("=======================")
    print("Menu: ")
    print("[1] Calculator")
    print("[2] Instructions")
    print("[3] Exit")
    print("=======================")
    choice = input("Please select an option: ")
    if choice == '1':
    calculator()
    elif choice == '2':
    instructions()
    elif choice == '3':
    print("Thank you for using Calculator.")
    break
    else:
    print("Not an option, try again:")





    share|improve this answer









    $endgroup$

















      7












      $begingroup$

      You are using function calls as if they were goto labels. That is a huge sin: it makes your program spaghetti code. If you want a loop, then write a loop. For example, main() should look like:



      def main():
      while True:
      #Menu
      print("=======================")
      print("Welcome to Calculator")
      print("By: Tyler Harris")
      print("=======================")
      print("Menu: ")
      print("[1] Calculator")
      print("[2] Instructions")
      print("[3] Exit")
      print("=======================")
      choice = input("Please select an option: ")
      if choice == '1':
      calculator()
      elif choice == '2':
      instructions()
      elif choice == '3':
      print("Thank you for using Calculator.")
      break
      else:
      print("Not an option, try again:")





      share|improve this answer









      $endgroup$















        7












        7








        7





        $begingroup$

        You are using function calls as if they were goto labels. That is a huge sin: it makes your program spaghetti code. If you want a loop, then write a loop. For example, main() should look like:



        def main():
        while True:
        #Menu
        print("=======================")
        print("Welcome to Calculator")
        print("By: Tyler Harris")
        print("=======================")
        print("Menu: ")
        print("[1] Calculator")
        print("[2] Instructions")
        print("[3] Exit")
        print("=======================")
        choice = input("Please select an option: ")
        if choice == '1':
        calculator()
        elif choice == '2':
        instructions()
        elif choice == '3':
        print("Thank you for using Calculator.")
        break
        else:
        print("Not an option, try again:")





        share|improve this answer









        $endgroup$



        You are using function calls as if they were goto labels. That is a huge sin: it makes your program spaghetti code. If you want a loop, then write a loop. For example, main() should look like:



        def main():
        while True:
        #Menu
        print("=======================")
        print("Welcome to Calculator")
        print("By: Tyler Harris")
        print("=======================")
        print("Menu: ")
        print("[1] Calculator")
        print("[2] Instructions")
        print("[3] Exit")
        print("=======================")
        choice = input("Please select an option: ")
        if choice == '1':
        calculator()
        elif choice == '2':
        instructions()
        elif choice == '3':
        print("Thank you for using Calculator.")
        break
        else:
        print("Not an option, try again:")






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered yesterday









        200_success200_success

        131k17156420




        131k17156420























            6












            $begingroup$

             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().






            share|improve this answer











            $endgroup$








            • 1




              $begingroup$
              Just to elaborate on the first point of why it is bad to keep calling main() - basically each time you call a method, you are 'entering' that method. But you never exit the method - you just keep going deeper into the wormhole with each main() call. As JH is saying, each time you call a method you are putting more data onto the stack, but since the methods never are allowed to exit, the data is never freed, which eventually means you run out of space and the application will stop working.
              $endgroup$
              – fabspro
              yesterday















            6












            $begingroup$

             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().






            share|improve this answer











            $endgroup$








            • 1




              $begingroup$
              Just to elaborate on the first point of why it is bad to keep calling main() - basically each time you call a method, you are 'entering' that method. But you never exit the method - you just keep going deeper into the wormhole with each main() call. As JH is saying, each time you call a method you are putting more data onto the stack, but since the methods never are allowed to exit, the data is never freed, which eventually means you run out of space and the application will stop working.
              $endgroup$
              – fabspro
              yesterday













            6












            6








            6





            $begingroup$

             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().






            share|improve this answer











            $endgroup$



             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().







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited yesterday

























            answered yesterday









            J_HJ_H

            4,692137




            4,692137







            • 1




              $begingroup$
              Just to elaborate on the first point of why it is bad to keep calling main() - basically each time you call a method, you are 'entering' that method. But you never exit the method - you just keep going deeper into the wormhole with each main() call. As JH is saying, each time you call a method you are putting more data onto the stack, but since the methods never are allowed to exit, the data is never freed, which eventually means you run out of space and the application will stop working.
              $endgroup$
              – fabspro
              yesterday












            • 1




              $begingroup$
              Just to elaborate on the first point of why it is bad to keep calling main() - basically each time you call a method, you are 'entering' that method. But you never exit the method - you just keep going deeper into the wormhole with each main() call. As JH is saying, each time you call a method you are putting more data onto the stack, but since the methods never are allowed to exit, the data is never freed, which eventually means you run out of space and the application will stop working.
              $endgroup$
              – fabspro
              yesterday







            1




            1




            $begingroup$
            Just to elaborate on the first point of why it is bad to keep calling main() - basically each time you call a method, you are 'entering' that method. But you never exit the method - you just keep going deeper into the wormhole with each main() call. As JH is saying, each time you call a method you are putting more data onto the stack, but since the methods never are allowed to exit, the data is never freed, which eventually means you run out of space and the application will stop working.
            $endgroup$
            – fabspro
            yesterday




            $begingroup$
            Just to elaborate on the first point of why it is bad to keep calling main() - basically each time you call a method, you are 'entering' that method. But you never exit the method - you just keep going deeper into the wormhole with each main() call. As JH is saying, each time you call a method you are putting more data onto the stack, but since the methods never are allowed to exit, the data is never freed, which eventually means you run out of space and the application will stop working.
            $endgroup$
            – fabspro
            yesterday

















            draft saved

            draft discarded
















































            Thanks for contributing an answer to Code Review Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            Use MathJax to format equations. MathJax reference.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f216557%2fcalculator-final-project-in-python%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Club Baloncesto Breogán Índice Historia | Pavillón | Nome | O Breogán na cultura popular | Xogadores | Adestradores | Presidentes | Palmarés | Historial | Líderes | Notas | Véxase tamén | Menú de navegacióncbbreogan.galCadroGuía oficial da ACB 2009-10, páxina 201Guía oficial ACB 1992, páxina 183. Editorial DB.É de 6.500 espectadores sentados axeitándose á última normativa"Estudiantes Junior, entre as mellores canteiras"o orixinalHemeroteca El Mundo Deportivo, 16 setembro de 1970, páxina 12Historia do BreogánAlfredo Pérez, o último canoneiroHistoria C.B. BreogánHemeroteca de El Mundo DeportivoJimmy Wright, norteamericano do Breogán deixará Lugo por ameazas de morteResultados de Breogán en 1986-87Resultados de Breogán en 1990-91Ficha de Velimir Perasović en acb.comResultados de Breogán en 1994-95Breogán arrasa al Barça. "El Mundo Deportivo", 27 de setembro de 1999, páxina 58CB Breogán - FC BarcelonaA FEB invita a participar nunha nova Liga EuropeaCharlie Bell na prensa estatalMáximos anotadores 2005Tempada 2005-06 : Tódolos Xogadores da Xornada""Non quero pensar nunha man negra, mais pregúntome que está a pasar""o orixinalRaúl López, orgulloso dos xogadores, presume da boa saúde económica do BreogánJulio González confirma que cesa como presidente del BreogánHomenaxe a Lisardo GómezA tempada do rexurdimento celesteEntrevista a Lisardo GómezEl COB dinamita el Pazo para forzar el quinto (69-73)Cafés Candelas, patrocinador del CB Breogán"Suso Lázare, novo presidente do Breogán"o orixinalCafés Candelas Breogán firma el mayor triunfo de la historiaEl Breogán realizará 17 homenajes por su cincuenta aniversario"O Breogán honra ao seu fundador e primeiro presidente"o orixinalMiguel Giao recibiu a homenaxe do PazoHomenaxe aos primeiros gladiadores celestesO home que nos amosa como ver o Breo co corazónTita Franco será homenaxeada polos #50anosdeBreoJulio Vila recibirá unha homenaxe in memoriam polos #50anosdeBreo"O Breogán homenaxeará aos seus aboados máis veteráns"Pechada ovación a «Capi» Sanmartín e Ricardo «Corazón de González»Homenaxe por décadas de informaciónPaco García volve ao Pazo con motivo do 50 aniversario"Resultados y clasificaciones""O Cafés Candelas Breogán, campión da Copa Princesa""O Cafés Candelas Breogán, equipo ACB"C.B. Breogán"Proxecto social"o orixinal"Centros asociados"o orixinalFicha en imdb.comMario Camus trata la recuperación del amor en 'La vieja música', su última película"Páxina web oficial""Club Baloncesto Breogán""C. B. Breogán S.A.D."eehttp://www.fegaba.com

            Vilaño, A Laracha Índice Patrimonio | Lugares e parroquias | Véxase tamén | Menú de navegación43°14′52″N 8°36′03″O / 43.24775, -8.60070

            Cegueira Índice Epidemioloxía | Deficiencia visual | Tipos de cegueira | Principais causas de cegueira | Tratamento | Técnicas de adaptación e axudas | Vida dos cegos | Primeiros auxilios | Crenzas respecto das persoas cegas | Crenzas das persoas cegas | O neno deficiente visual | Aspectos psicolóxicos da cegueira | Notas | Véxase tamén | Menú de navegación54.054.154.436928256blindnessDicionario da Real Academia GalegaPortal das Palabras"International Standards: Visual Standards — Aspects and Ranges of Vision Loss with Emphasis on Population Surveys.""Visual impairment and blindness""Presentan un plan para previr a cegueira"o orixinalACCDV Associació Catalana de Cecs i Disminuïts Visuals - PMFTrachoma"Effect of gene therapy on visual function in Leber's congenital amaurosis"1844137110.1056/NEJMoa0802268Cans guía - os mellores amigos dos cegosArquivadoEscola de cans guía para cegos en Mortágua, PortugalArquivado"Tecnología para ciegos y deficientes visuales. Recopilación de recursos gratuitos en la Red""Colorino""‘COL.diesis’, escuchar los sonidos del color""COL.diesis: Transforming Colour into Melody and Implementing the Result in a Colour Sensor Device"o orixinal"Sistema de desarrollo de sinestesia color-sonido para invidentes utilizando un protocolo de audio""Enseñanza táctil - geometría y color. Juegos didácticos para niños ciegos y videntes""Sistema Constanz"L'ocupació laboral dels cecs a l'Estat espanyol està pràcticament equiparada a la de les persones amb visió, entrevista amb Pedro ZuritaONCE (Organización Nacional de Cegos de España)Prevención da cegueiraDescrición de deficiencias visuais (Disc@pnet)Braillín, un boneco atractivo para calquera neno, con ou sen discapacidade, que permite familiarizarse co sistema de escritura e lectura brailleAxudas Técnicas36838ID00897494007150-90057129528256DOID:1432HP:0000618D001766C10.597.751.941.162C97109C0155020