Tuesday, July 19, 2022

Simple Python Calculator

 My background is C - system programming. Switching to Python with so much libraries and functionalities make it a little over whelming. I wrote a simple calculator that rhythms with code we normally write with C. 


First I wrote a simple calculator function, very straight you can practice by changing if to switch statement 

import os


def Calculation(a, b, operation):

    if(operation=='+'):

        return(a+b);

    if(operation=='-'):

        return(a-b);

    if(operation=='*'):

        return(a*b);

    if(operation=='/'):

        return(a/b);



Below is the similar to the main program of 'C'.

while(1):

    

    print('Welcome to Sam''s Calculator \n')

    print('Press Q any time to exit the calcultaor \n')

    a = input('Please enter the first input =  ')

    b = input('Please enter the second input =  ')

    op= input('Please select the operation to be performed =  ')

    

    if(a=='Q'or a=='q' or b=='Q' or b=='q' or op=='Q' or op=='q' ):

        print('Thank you for using Sam''s Simple calcultaor. Calculator is now exiting \n')

        break

    a = int(a)

    b = int(b)

    result= Calculation(a,b, op)


    print("Result of the operation ",op," = ",result)

Popular Posts