How to Make a Simple Calculator Using Python

Spread the love

In this tutorial, I’ll show you how to make a simple calculator using python. Let’s make a simple calculator using python. this will be a simple python script, not GUI. I’ll also post the code of GUI as well. this is a completely beginner-friendly project.

to make a simple calculator using python we need the basic knowledge of functions and conditional statements.

we will start with creating a function named calculator that takes three arguments first number, second number and sign of operator.

def calculator(num1, num2, sign):

Here is our function calculator. now we use conditional statements to perform certain operations based on the sign given as argument.

like, if the sign is ‘+’ then we simply add number1 and number2. if the sign is ‘-‘ then we subtract that two numbers. and do the same way for other signs as well.

to do this we have to use if and elif statements in this manner,

    if sign == "+":
        return num1+num2
    elif sign == "-":
        return num1 - num2

Do this same thing for *, /, %, // as well. finally we have to call this function with all required arguments.

now our final code looks like this,

def calculator(num1, num2, sign):
    if sign == "+":
        return num1+num2
    elif sign == "-":
        return num1 - num2
    elif sign == "*":
        return num1 * num2
    elif sign == "/":
        return num1 / num2
    elif sign == "%":
        return num1 % num2
    elif sign == "//":
        return num1 // num2
    
print(calculator(5,2,"*"))

while calling function first and the second argument will be number and the last argument we have to pass is an operator as a string.

if we run our above code we will get 10 as output.

How to Make a Simple Calculator Using Python - papa programmer

Related post: Operators In Python

Still wondering how to get started with python?

Check out our exclusive book,

How to Make a Simple Calculator Using Python - Papa Programmer

Spread the love
Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like