Automationscribe.com
  • Home
  • AI Scribe
  • AI Tools
  • Artificial Intelligence
  • Contact Us
No Result
View All Result
Automation Scribe
  • Home
  • AI Scribe
  • AI Tools
  • Artificial Intelligence
  • Contact Us
No Result
View All Result
Automationscribe.com
No Result
View All Result

Utilizing Python to Construct a Calculator

admin by admin
September 17, 2025
in Artificial Intelligence
0
Utilizing Python to Construct a Calculator
399
SHARES
2.3k
VIEWS
Share on FacebookShare on Twitter


Calculators date again to the seventeenth century, with the primary calculator created within the type of a mechanical machine. Over time, these calculators developed in order that extra individuals might use them. It was within the Sixties, that the primary digital calculator got here into being, and as time went on, the calculator was built-in into our computer systems and now mobiles.

Both bodily or digital, we reside in a time the place every of us has used a calculator. Whether or not we’re calculating lease, totalling the invoice, or discovering the ultimate share of our youngsters’ outcomes, all of us have taken assist from the calculator.

Let’s make the most of Python fundamentals, together with features, conditional statements, dictionaries, and loops, to create our model of a calculator.

Working of our Calculator

Our calculator will work as follows:

  1. It would ask the consumer for a quantity
  2. It would then ask the consumer for the operation
  3. It would ask the consumer for the second quantity
  4. It would carry out its calculations and print the output
  5. It would ask the consumer in the event that they wish to stick with it with this quantity (like our bodily calculator) or begin throughout
  6. If the consumer asks to begin throughout, it’s going to restart the above course of
  7. If the consumer desires to hold on with the consequence, it’s going to take this quantity as the primary and ask for the operation, after which observe as the primary time.

Allow us to assemble the above thought course of right into a flowchart for higher understanding:

Flowchart (Picture by Writer)

Defining Operation Capabilities

Initially, we are going to outline features that will likely be known as when their corresponding operation image is chosen by the consumer. We’ll outline features add for addition, subtract for subtraction, multiply for multiplication, and divide for division. These features will take the 2 numbers as their enter parameters, and carry out the chosen operation on them, and return the consequence.

def add(num1, num2):
    return num1 + num2


def subtract(num1, num2):
    return num1 - num2


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


def divide(num1, num2):
    return num1/num2

Making a Dictionary of Operations

Allow us to additionally create a dictionary of operations. The operation symbols will likely be saved as keys, and the identify of the operation, that can also be the identify of the perform, will likely be saved as the worth to that key. We’ll ask the consumer to decide on an operation, and primarily based on their selection, the precise operation perform that we’ve outlined above will likely be known as.

operations = {
    "+": add,
    "-": subtract,
    "*": multiply,
    "/": divide,
}

Asking Consumer for Enter

As soon as we’ve outlined our features, allow us to now ask the consumer for his or her first quantity num1, their chosen operation operation_symbol, and their second quantity num2:

num1 = float(enter("What's the first quantity?: "))
for image in operations:
            print(image)
operation_symbol = enter("Choose an operation: ")
num2 = float(enter("What's the subsequent quantity?: "))

Discover that we’ve transformed the enter numbers to the float sort. Additionally, we’ve created the for loop that can iterate over the keys within the operations dictionary we’ve outlined earlier on, and print every operation image.

Calculating and Displaying the Reply

Subsequent, is to calculate the reply and print it out to the consumer in its full kind. The next code will likely be used for this objective:

reply = operations[operation_symbol](num1, num2)
print(f"{num1} {operation_symbol} {num2} = {reply}")

The reply variable will retailer the worth that we’ve bought from calling the related perform, based on the operation image chosen. We now have used an f-string to correctly format the output assertion.

Verify Calculator Continuity with the Whereas Loop

Now that we’ve calculated and displayed the consequence, the following step is to test if the consumer desires to proceed utilizing the calculator by carrying on the consequence worth reply onwards or desires to begin the calculator throughout. For this objective, we are going to outline a variable should_accumulate that will likely be True when the consumer desires to proceed and will likely be False when the consumer doesn’t wish to proceed, quite it’s going to restart the calculator. The should_accumulate variable will likely be outlined earlier in our code.

should_accumulate = True

whereas should_accumulate:
    ...
    selection = enter(f"Kind 'y' to proceed calculating with {reply}, or sort 'n' to begin a brand new calculation: ")

        if selection == "y":
            num1 = reply
        else:
            should_accumulate = False
            print("n" * 20)
            

Because the should_accumulate variable is True, and we’ve added a whereas loop, the code throughout the loop will proceed to run, except the consumer selects ‘n’. When the consumer selects ‘n’, the calculation won’t carry onwards, however will cease, and we are going to seemingly begin a brand new console by typing 20 strains. However now we wish to restart the calculator, so for this objective, we are going to use a Python perform idea known as recursion.

For the calculator to restart, we are going to outline it as a perform, and it will likely be known as after we wish to restart the calculator perform with out carrying on the consequence. This will likely be coded as a recursive perform. Recursion in Python permits a perform to be known as inside itself, similar to we are going to do under:

def calculator():
    should_accumulate = True
    num1 = float(enter("What's the first quantity?: "))

    whereas should_accumulate:
        for image in operations:
            print(image)
        operation_symbol = enter("Choose an operation: ")
        num2 = float(enter("What's the subsequent quantity?: "))
        reply = operations[operation_symbol](num1, num2)
        print(f"{num1} {operation_symbol} {num2} = {reply}")

        selection = enter(f"Kind 'y' to proceed calculating with {reply}, or sort 'n' to begin a brand new calculation: ")

        if selection == "y":
            num1 = reply
        else:
            should_accumulate = False
            print("n" * 20)
            calculator()

Discover we’ve known as the calculator perform contained in the calculator perform itself. For the code to run for the primary time, we have to name it exterior.

Take a look at this hyperlink to entry the whole code: https://github.com/MahnoorJaved98/Utilizing-Python-to-Construct-a-Calculator

Conclusion

On this brief tutorial, we’ve efficiently realized tips on how to construct a calculator in Python, with the power to carry out the fundamental 4 operations on addition, subtraction, multiplication and division. We now have achieved this utilizing our primary information of features, loops, and recursive features.

Tags: BuildCalculatorPython
Previous Post

Streamline entry to ISO-rating content material modifications with Verisk ranking insights and Amazon Bedrock

Leave a Reply Cancel reply

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

Popular News

  • How Aviva constructed a scalable, safe, and dependable MLOps platform utilizing Amazon SageMaker

    How Aviva constructed a scalable, safe, and dependable MLOps platform utilizing Amazon SageMaker

    402 shares
    Share 161 Tweet 101
  • Unlocking Japanese LLMs with AWS Trainium: Innovators Showcase from the AWS LLM Growth Assist Program

    401 shares
    Share 160 Tweet 100
  • Diffusion Mannequin from Scratch in Pytorch | by Nicholas DiSalvo | Jul, 2024

    401 shares
    Share 160 Tweet 100
  • Streamlit fairly styled dataframes half 1: utilizing the pandas Styler

    401 shares
    Share 160 Tweet 100
  • Proton launches ‘Privacy-First’ AI Email Assistant to Compete with Google and Microsoft

    401 shares
    Share 160 Tweet 100

About Us

Automation Scribe is your go-to site for easy-to-understand Artificial Intelligence (AI) articles. Discover insights on AI tools, AI Scribe, and more. Stay updated with the latest advancements in AI technology. Dive into the world of automation with simplified explanations and informative content. Visit us today!

Category

  • AI Scribe
  • AI Tools
  • Artificial Intelligence

Recent Posts

  • Utilizing Python to Construct a Calculator
  • Streamline entry to ISO-rating content material modifications with Verisk ranking insights and Amazon Bedrock
  • Constructing a Unified Intent Recognition Engine
  • Home
  • Contact Us
  • Disclaimer
  • Privacy Policy
  • Terms & Conditions

© 2024 automationscribe.com. All rights reserved.

No Result
View All Result
  • Home
  • AI Scribe
  • AI Tools
  • Artificial Intelligence
  • Contact Us

© 2024 automationscribe.com. All rights reserved.