Page 1 of 1

Creating a console based Calculator in Python.

#1 Sergio Tapia  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1253
  • View blog
  • Posts: 4,168
  • Joined: 27-January 10

Posted 05 November 2010 - 10:30 AM

I'll show how to make a terminal based Python calculator program.

We’ll be creating a little calculator script in Python using the console. You’ll see how to use the while loop, how to convert strings to ints and all sorts of wizardry the likes of which the world has never seen the likes of which.

Creating our helper functions.

First let’s create a little method that we’ll use to convert strings. It’s simple: If you can convert to int, convert it, if you cannot, convert it to a float.
Here what it looks like:

def convertString(str):
    try:
        returnValue = int(str)
    except ValueError:
        returnValue = float(str)
    return returnValue



Now let’s define the four little methods that account for the basic arithmetic our application will do:

def addition(a, B)/>:
    return convertString(a) + convertString(B)/>

def subtraction(a, B)/>:
    return convertString(a) - convertString(B)/>

def multiplication(a, B)/>:
    return convertString(a) * convertString(B)/>

def division(a, B)/>:
    return convertString(a) / convertString(B)/>



Notice we’re calling our helper method, convertString; and not the builtin Python method ‘int()’.


Looping keeps things running

We’ll declare a little boolean flag variable to let us know if we should keep running this application or not. We’ll call it keepProgramRunning.

keepProgramRunning = True

print "Welcome to the Calculator!"

while keepProgramRunning:
    #Whatever is in here will run until the end of time
    #or until the variable is false. Whichever comes first.



Let’s create a little console menu so our users can choose what to do.

keepProgramRunning = True

print "Welcome to the Calculator!"

while keepProgramRunning:
    print "Please choose what you'd like to do:"

    print "0: Addition"
    print "1: Subtraction"
    print "2: Multiplication"
    print "3: Division"
    print "4: Quit Application"    

    #Capture the menu choice.
    choice = raw_input()    

    if choice == "0":
        #Something goes here.
    elif choice == "1":
        #Ditto.
    elif choice == "2":
        #Another option
    elif choice == "3":
        #What?
    elif choice == "4":
        print "Bye!"
        keepProgramRunning = False
    else:
        print "Please choose a valid option."
        print "\n"



Let’s break this down, we’re capturing the input and then using if statements to determine where we’re going. If the if statements don’t find a suitable response, you just tell the user to stop being so dumb and choose something that would work.

Remember, since this is all inside of the while loop and the keeProgramRunning variable hasn’t been touched, what will happen when it reaches the end of the script? That’s right! It’ll display the menu again and prompt the user for input.

Only when a user chooses ’4′ will the program end, and that’s because we’re changing the keepProgramRunning variable to False, which let’s us break free from the constricting While loop.

Now let’s fill in the if statements and give them something to do:

def convertString(str):
    try:
        returnValue = int(str)
    except ValueError:
        returnValue = float(str)
    return returnValue

def addition(a, B)/>:
    return convertString(a) + convertString(B)/>

def subtraction(a, B)/>:
    return convertString(a) - convertString(B)/>

def multiplication(a, B)/>:
    return convertString(a) * convertString(B)/>

def division(a, B)/>:
    return convertString(a) / convertString(B)/>

keepProgramRunning = True

print "Welcome to the Calculator!"

while keepProgramRunning:
    print "Please choose what you'd like to do:"

    print "0: Addition"
    print "1: Subtraction"
    print "2: Multiplication"
    print "3: Division"
    print "4: Quit Application"    

    #Capture the menu choice.
    choice = raw_input()    

    if choice == "0":
        numberA = raw_input("Enter your first number: ")
        numberB = raw_input("Enter your second number: ")
        print "Your result is:"
        print addition(numberA, numberB)
    elif choice == "1":
        numberA = raw_input("Enter your first number: ")
        numberB = raw_input("Enter your second number: ")
        print "Your result is:"
        print subtraction(numberA, numberB)
    elif choice == "2":
        numberA = raw_input("Enter your first number: ")
        numberB = raw_input("Enter your second number: ")
        print "Your result is:"
        print multiplication(numberA, numberB)
    elif choice == "3":
        numberA = raw_input("Enter your first number: ")
        numberB = raw_input("Enter your second number: ")
        print "Your result is:"
        print division(numberA, numberB)
    elif choice == "4":
        print "Bye!"
        keepProgramRunning = False
    else:
        print "Please choose a valid option."
        print "\n"



We capture the input, save it to a variable, give the two variables to our method and voila – you’re very first calculator in Python.

Hope you liked this brief tutorial.

------------------------------------------------------

If you liked this tutorial, you can read more articles written by me at my blog. Visit AlphaOT

Is This A Good Question/Topic? 3
  • +

Replies To: Creating a console based Calculator in Python.

#2 Ticon  Icon User is offline

  • D.I.C Regular

Reputation: 28
  • View blog
  • Posts: 320
  • Joined: 20-August 09

Posted 22 January 2011 - 11:35 PM

wrong section partner, this should have been created in the tutorials section of pyhon. But great tutorial
Was This Post Helpful? 0
  • +
  • -

#3 no2pencil  Icon User is offline

  • Admiral Fancy Pants
  • member icon

Reputation: 5388
  • View blog
  • Posts: 27,383
  • Joined: 10-May 07

Posted 22 January 2011 - 11:43 PM

View PostTicon, on 23 January 2011 - 01:35 AM, said:

wrong section partner, this should have been created in the tutorials section of pyhon.

Attached Image

...this is posted in python tutorials.
Was This Post Helpful? 0
  • +
  • -

#4 Ticon  Icon User is offline

  • D.I.C Regular

Reputation: 28
  • View blog
  • Posts: 320
  • Joined: 20-August 09

Posted 23 January 2011 - 10:01 AM

Maybe a site bug then? I found it under the python help forum. My bad on miscalling.
Was This Post Helpful? 0
  • +
  • -

#5 amritasenthilkumar  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 08-August 12

Posted 08 August 2012 - 01:11 AM

import Tkinter as tk
from Tkinter import *
import tkMessageBox
root = Tk()
buttons = {}
signVal = ''
firstVal = 1
root.title('Calculator')
root.attributes("-toolwindow", 1)

def createNumbers():
    global buttons
    buttonNum = 0
  
    for b in range( 2 ):
        for b2 in range( 5 ):
            button = Button(frame2, text = buttonNum, font = "Courier 9", width = 5, bd = 3 )
            button.grid(row=b, column=b2)
            buttons[ button ] = buttonNum
            buttonNum += 1
            button.bind( "<Button-1>", makeChoice )


def operators():
    button = Button(frame2, text = '+', font = "Courier 9", width = 5, bd = 3, command = lambda : operation('+') )
    button.grid(row=2, column=0)
    button = Button(frame2, text = '-', font = "Courier 9", width = 5, bd = 3, command = lambda : operation('-') )
    button.grid(row=2, column=1)
    button = Button(frame2, text = '*', font = "Courier 9", width = 5, bd = 3, command = lambda : operation('*') )
    button.grid(row=2, column=2)
    button = Button(frame2, text = '/', font = "Courier 9", width = 5, bd = 3, command = lambda : operation('/') )
    button.grid(row=2, column=3)
    button = Button(frame2, text = '=', font = "Courier 9", width = 5, bd = 3, command = lambda : excutionPart('=') )
    button.grid(row=2, column=4)
    button = Button(frame2, text = 'Clear', font = "Courier 9", width = 5, bd = 3, command = lambda : clearAll('clear') )
    button.grid(row=3, column=0)

def makeChoice( event ):
    global buttons    
    if (v.get() is None) or (len(v.get()) == 0):
       v.set(buttons[ event.widget ])       
    else:
        v.set(str(v.get())+str(buttons[ event.widget ]))
        
def operation(value):
    try:        
        global signVal
        global firstVal
        signVal = value
        if not isinstance(v.get(), int):
            firstVal = int(v.get())
        else:
            tkMessageBox.showerror("Error","Wrong Formate")
        print "First Value :", firstVal
        v.set('')
    except TypeError:
        tkMessageBox.showerror("Error","Wrong Formate")
   

def excutionPart(ex):
    print "Second Value :", str(v.get())
    if signVal is '+':
        v.set(int(firstVal)+int(v.get()))
    elif signVal is '-':
        v.set(int(firstVal)-int(v.get()))
    elif signVal is '*':
        v.set(int(firstVal)*int(v.get()))
    elif signVal is '/':
        v.set(int(firstVal)/int(v.get()))
    else:
        v.set('')
    print "Result is :", str(v.get())

def clearAll(val):
    v.set('')


#Top Frame 
frame1 = Frame(root)
frame1.pack(side = TOP)

#Bottom Frame 
frame2 = Frame(root)
frame2.pack(side = BOTTOM)

v = StringVar()
e = Entry(frame1, textvariable=v, width = 30)
e.pack(side = LEFT)

    
            
createNumbers()
operators()
    
root.mainloop()

This post has been edited by JackOfAllTrades: 08 August 2012 - 01:31 PM
Reason for edit:: Added code tags

Was This Post Helpful? 0
  • +
  • -

#6 kingmak  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 17-March 13

Posted 17 March 2013 - 10:48 PM

The code itself is pretty good, but I found some logical errors: 1) using int rather then float 2) what would happen if a curious guy like me would divide by zero?

anyways I fixed up the code somewhat and added some some fun to it. Here is the code:
import os, time

os.system("Title Mak's Calc")
os.system("color f2")

keepGoing = True 

def addition(num1, num2):
    return float(num1) + float(num2)

def subtraction(num1, num2):
    return float(num1) - float(num2)

def multiply(num1, num2):
    return float(num1) * float(num2)

def division(num1, num2):
    return float(num1) / float(num2)

while (keepGoing):

    print('')
    print(' Welcome to Mak\'s Calculator')
    print('')
    print(' Please Choose from the following options: ')
    print('')
    print(' 1 = Addition')
    print(' 2 = Subtraction')
    print(' 3 = Multiplication')
    print(' 4 = Division')
    print(' 5 = Quit Application')
    print('')
    
    choice = raw_input(" ")
    print ('')
    
    if choice == "1":
        num1 = raw_input(' Enter the first number here: ')
        num2 = raw_input(' Enter the second number here: ')
        print ('')
        print (' The result is:'), addition(num1, num2)
        print ('')
        print (' ------------------------------------------------------------------------------ ')
        time.sleep(1.5)
    
    elif choice == "2":
        num1 = raw_input(' Enter the first number here: ')
        num2 = raw_input(' Enter the second number here: ')
        print ('')
        print (' The result is:'), subtraction(num1, num2)
        print ('')
        print (' ------------------------------------------------------------------------------ ')        
        time.sleep(1.5)

    elif choice == "3":
        num1 = raw_input(' Enter the first number here: ')
        num2 = raw_input(' Enter the second number here: ')
        print ('')
        print (' The result is:'), multiply(num1, num2)
        print ('')
        print (' ------------------------------------------------------------------------------ ')        
        time.sleep(1.5)

    elif choice == "4":
        num1 = raw_input(' Enter the first number here: ')
        num2 = raw_input(' Enter the second number here: ')
        
        if (num2 == "0"):
            print('')
            print(' Sorry I can\'t divide by Zero, Let\'s try again')
            print ('')
            print (' ------------------------------------------------------------------------------ ')
            time.sleep(4)
            pass
        else:
            print ('')
            print (' The result is:'), division(num1, num2)
            print ('')
            print (' ------------------------------------------------------------------------------ ')        
            time.sleep(1.5)

    elif choice == "5":
        print(" Quitting From Application")
        time.sleep(4)
        keepGoing = False
        quit()

    else:
        print (" Please Choose a valid number from the given choices" + "\n")
        print ('')
        print (' ------------------------------------------------------------------------------ ')
        time.sleep(1.5)



Was This Post Helpful? 0
  • +
  • -

#7 Akitta  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 02-September 13

Posted 04 September 2013 - 04:05 PM

I got that many Errors.. It is probably me.

def subtraction(a, B)/>: "The '/' and '>' were coming up as syntax error, So was 'elif'". I tried changeing them. I deleted '/' & '>' and changed 'elif' to 'if', But i was getting indent errors after this.

I will do it again tomorrow when i'm not so tired .
I'm using Python 2.7.3. Could that be an Issue?
Sorry to be so NooB =)
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1