Python Forum
Python Calculator Application
Thread Rating:
  • 2 Vote(s) - 3 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python Calculator Application
#1
I made a simple calculator application in Python over the course of around an hour and a half today. Is there anything that I could improve on in terms of simplicity or better ways of getting the job done? Thanks! (I started learning Python earlier this week, but I've worked with other languages in the past).

# This is a simple calculator application.
# Nolan Welch
import time #This is needed in order to space out the output so the user isn't overwhelmed.
time.sleep(1)
print("Python Calculator made by Nolan Welch, 7/21/2017.\n\n\n")
time.sleep(2.5)
# Defining the calculator function, which is used to make all the calculations based on user input
def calculator():
   var1 = input("Enter first number:  ")
   var2 = input("Enter second number:  ")
   if (checkIfInt(var1) and checkIfInt(var2)):
       var1 = int(var1)
       var2 = int(var2)
       if (userInput == "*"):
           print("The product of the first and second number is " + str(mul(var1, var2)))
       elif (userInput == "/"):
           print("The first number divided by the second number is " + str(div(var1, var2)))
       elif (userInput == "+"):
           print("The sum of the first and second numbers is " + str(add(var1, var2)))
       elif(userInput == "-"):
           print("The first number minus the second number is " + str(sub(var1, var2)))
       else:
           print("Invalid input.")
           time.sleep(2)
           main()
   else:
       print("Both inputs must be integers.\nTaking you back to the calculator...")
       time.sleep(2)
       calculator()
def add(num1, num2):
   return(num1 + num2)
def mul(num1, num2):
   return(num1 * num2)
def div(num1, num2):
   return(num1 / num2)
def sub(num1, num2):
   return(num1 - num2)
# Defining a function that checks whether or not the input is an integer(used in the calculator function)
def checkIfInt(possibleInt):
   try:
       val = int(possibleInt)
       return True
   except ValueError:
       return False
# After the entire program has been run, this function checks whether or not the user would like to use the calculator again
def again():
   repeat = input("Would you like to use the calculator again?  ").lower()
   if(repeat == "y" or repeat == "yes"):
       main()
   elif(repeat == "n" or repeat == "no"):
       print("See you next time!")
       time.sleep(2)
       quit()
   else:
       while(True):
           print("Sorry, invalid input.")
           time.sleep(1)
           again()
def main():
   global userInput
   userInput = input("Which mathematical function would you like to do? Insert *, /, +, or -. Type HELP for help.  ")
   if(userInput == "HELP"):
       print("\n* = Multiplication\n/ = Division\n+ = Addition\n- = Subtraction")
       secondaryInput = input("\nType \"BACK\" to go back to the calculator.  ")
       if (secondaryInput == "BACK"):
           main()
       else:
           while(True):
               backInput = input("Invalid input. Please type \"BACK\" to return to the calculator.  ")
               if(backInput == "BACK"):
                   main()
   # Making sure that the user inputs one of the four accepted operators
   elif (userInput != "*" and userInput != "/" and userInput != "+" and userInput != "-"):
       print("Invalid input!")
       time.sleep(2)
       main()
   else:
       calculator()
   again()
main()
""" This entire program seems to be out of order, but I put some functions before others for the sake of
   simplicity in the final code and in an effort to avoid errors.
"""
Reply
#2
(Jul-21-2017, 04:23 PM)MemeStealer Wrote: Is there anything that I could improve on in terms of simplicity or better ways of getting the job done?
Yes Cool
The effort is good,but there are really big problem is your design of this.
I will not at all try to fix your code,but give a example with design in focus.
It's scary that you call the main() function 14 times Dodgy

Some point i name the function menu() not main(),
a lot people use main() but name no sense because it can be everything.
menu() is just called 1 time,after calculate always fall back into menu() again.
There can make new calculation or Quit out.
from operator import add, sub, mul

def calc():
   op = input("Enter operator +-*: ")
   n1 = int(input('Fist number: '))
   n2 = int(input('Second number: '))
   operators = {'+': add(n1, n2), '-': sub(n1, n2), '*': mul(n1, n2)}
   if op in operators:
       print('{} {} {} = {}'.format(n1, op, n2, operators[op]))
   input('Press enter to return menu\n')

def menu():
   while True:
       print('(1) Calculate 2 numbers')
       print('(Q) Quit')
       choice = input('Enter your choice: ').lower()
       if choice == '1':
           calc()
       elif choice == 'q':
           return False
       else:
           print('Not a correct choice: <{}>,try again'.format(choice))

if __name__ == '__main__':
   menu()
A run:
Output:
C:\1_py\div λ python calc.py (1) Calculate 2 numbers (Q) Quit Enter your choice: aaaa Not a correct choice: <aaaa>,try again (1) Calculate 2 numbers (Q) Quit Enter your choice: 1 Enter operator +-*: * Fist number: 6 Second number: 7 6 * 7 = 42 Press enter to return menu (1) Calculate 2 numbers (Q) Quit Enter your choice: q C:\1_py\div λ
Reply
#3
(Jul-21-2017, 04:23 PM)MemeStealer Wrote:
def checkIfInt(possibleInt):
   try:
       val = int(possibleInt)
       return True
   except ValueError:
       return False

What about str.isdigit()?
def checkIfInt(possibleInt):
    return possibleInt.isdigit()

>>> checkIfInt("42")
True
>>> checkIfInt("k13")
False
>>> checkIfInt("8.4")
False
As snippsat pointed out, the operator module could make things much cleaner for you: https://docs.python.org/3/library/operator.html
Reply
#4
(Jul-21-2017, 06:36 PM)nilamo Wrote: What about str.isdigit()?  
def checkIfInt(possibleInt):
    return possibleInt.isdigit()

>>> checkIfInt("42")
True
>>> checkIfInt("k13")
False
>>> checkIfInt("8.4")
False
Yeah, that does look a lot cleaner and easier to understand than my original code. Is that a function pre-built into Python?
(Jul-21-2017, 06:36 PM)nilamo Wrote: As snippsat pointed out, the operator module could make things much cleaner for you: https://docs.python.org/3/library/operator.html
I noticed that I had a lot of code that was basically pointless, accomplishing nothing that a non-function operator couldn't do:
def add(num1, num2):
  return(num1 + num2)
def mul(num1, num2):
  return(num1 * num2)
def div(num1, num2):
  return(num1 / num2)
def sub(num1, num2):
  return(num1 - num2)
I'm not entirely sure where my mind was when I did this, but that portion of the code has been replaced.
Reply
#5
Most programs are written so that they're actually libraries. A "main" function is an entry point if you try to run the program directly, which then calls the libraries functions.
Structuring it this way makes it easy to do a lot of things, such as share your code with someone else (they can just "import" your code and call some functions, without your program starting to do it's things), or for testing.

If the "main" function is being called more than once, it's normally a red flag that something's a little fishy with the code.
Reply
#6
(Jul-21-2017, 06:03 PM)snippsat Wrote: It's scary that you call the main() function 14 times Dodgy
I don't think I fully understand the purpose of the main function. Where, why, and how often should I call this function?

(Jul-21-2017, 06:03 PM)snippsat Wrote: Some point i name the function menu() not main(),
a lot people use main() but name no sense because it can be everything.
menu() is just called 1 time,after calculate always fall back into menu() again.
There can make new calculation or Quit out.
I'll take your advice and make a menu() function as opposed to referencing the main() function as many times as I have.
Thanks for the help!
Reply
#7
(Jul-21-2017, 07:08 PM)nilamo Wrote: Most programs are written so that they're actually libraries.  A "main" function is an entry point if you try to run the program directly, which then calls the libraries functions.
Structuring it this way makes it easy to do a lot of things, such as share your code with someone else (they can just "import" your code and call some functions, without your program starting to do it's things), or for testing.

If the "main" function is being called more than once, it's normally a red flag that something's a little fishy with the code.

Thanks!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Need some help trying to get my Python mortgage amortization calculator to work prope IamSirAskAlot 4 15,771 Feb-12-2024, 10:53 PM
Last Post: BerniceBerger
  How do I properly implement restarting a multithreaded python application? MrFentazis 1 630 Jul-17-2023, 09:10 PM
Last Post: JamesSmith
  Python running only in application Mawixy 2 1,138 Apr-19-2022, 11:38 AM
Last Post: Mawixy
  New to python, trying to make a basic calculator AthertonH 2 1,145 Apr-14-2022, 03:33 PM
Last Post: AthertonH
  How To Create A "Birthday Calculator" in Python? unigueco9 3 3,717 Oct-11-2021, 08:03 PM
Last Post: SamHobbs
  How to send data from a python application to an external application aditya_rajiv 1 2,183 Jul-26-2021, 06:00 AM
Last Post: ndc85430
  python calculator only using decomposing functions kirt6405 1 1,773 Jun-19-2021, 12:52 AM
Last Post: bowlofred
  python application and credentials safety concern aster 4 3,531 Mar-06-2021, 06:51 PM
Last Post: snippsat
  Keep Application running after Python script ends PEGylated_User 0 1,987 Nov-12-2020, 03:27 PM
Last Post: PEGylated_User
  Installing Python Application pplgf 3 2,558 Apr-27-2020, 10:51 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020