Results 1 to 1 of 1

Thread: [Python] Calculator

  1. #1

    Thread Starter
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    11,711

    [Python] Calculator

    Description:
    This is a very simple calculator using Python 3.3.2. It uses the command prompt, similar to Visual Basic.Net's console application.


    Notes:
    You can easily convert this to compile with Python 2, just change input() to raw_input()


    Plans:
    I plan to properly parse the numeric datatypes. Currently I'm just using int([string]), which is fine if the user enters in a numeric data type, but if the user enters in a non-numeric character then it will crash the program.


    Source:
    Python Code:
    1. #The add, subtract, multiply, and divide functions
    2. def add(x, y):
    3.     return x + y
    4.    
    5. def sub(x, y):
    6.     return x - y
    7.    
    8. def multiply(x, y):
    9.     return x * y
    10.    
    11. def divide(x, y):
    12.     return x / y
    13.    
    14. #Infinite loop
    15. main = True
    16. while main == True:
    17.     #Get values for the x and y parameters for the functions above.
    18.     x = int(input("Value 1: "))
    19.     y = int(input("Value 2: "))
    20.    
    21.     getoperation = True
    22.     while getoperation == True:
    23.         #The print out should be:
    24.         #What would you like to do?
    25.         #Add = +
    26.         #Subtract = -
    27.         #Multiply = *
    28.         #Divide = /
    29.         #
    30.         #
    31.        
    32.         operation = input("What would you like to do?\nAdd = +\nSubtract = -\nMultiply = *\nDivide = /\n\n")
    33.        
    34.         #Get the operation and preform the function accordingly
    35.         if operation == "+":
    36.             getoperation = False
    37.             print (str(x) + " + " + str(y) + " = " + str(add(x, y)))
    38.         elif operation == "-":
    39.             getoperation = False
    40.             print (str(x) + " - " + str(y) + " = " + str(sub(x, y)))
    41.         elif operation == "*":
    42.             getoperation = False
    43.             print (str(x) + " * " + str(y) + " = " + str(multiply(x, y)))
    44.         elif operation == "/":
    45.             getoperation = False
    46.             print (str(x) + " / " + str(y) + " = " + str(divide(x, y)))
    47.         else:
    48.             #If the user entered in something other than +-*/ then repeat
    49.             print ("Invalid Input")
    Last edited by dday9; Oct 16th, 2013 at 09:42 AM.
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | Code Tags | Sword of Fury - Jameram

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width