Close Menu
    Trending
    • TDS Newsletter: How Compelling Data Stories Lead to Better Business Decisions
    • I Measured Neural Network Training Every 5 Steps for 10,000 Iterations
    • “The success of an AI product depends on how intuitively users can interact with its capabilities”
    • How to Crack Machine Learning System-Design Interviews
    • Music, Lyrics, and Agentic AI: Building a Smart Song Explainer using Python and OpenAI
    • An Anthropic Merger, “Lying,” and a 52-Page Memo
    • Apple’s $1 Billion Bet on Google Gemini to Fix Siri
    • Critical Mistakes Companies Make When Integrating AI/ML into Their Processes
    ProfitlyAI
    • Home
    • Latest News
    • AI Technology
    • Latest AI Innovations
    • AI Tools & Technologies
    • Artificial Intelligence
    ProfitlyAI
    Home » Using Python to Build a Calculator
    Artificial Intelligence

    Using Python to Build a Calculator

    ProfitlyAIBy ProfitlyAISeptember 16, 2025No Comments6 Mins Read
    Share Facebook Twitter Pinterest LinkedIn Tumblr Reddit Telegram Email
    Share
    Facebook Twitter LinkedIn Pinterest Email


    Calculators date again to the seventeenth century, with the primary calculator created within the type of a mechanical system. 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 stay 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’ll ask the person for a quantity
    2. It’ll then ask the person for the operation
    3. It’ll ask the person for the second quantity
    4. It’ll carry out its calculations and print the output
    5. It’ll ask the person in the event that they wish to keep it up with this quantity (like our bodily calculator) or begin throughout
    6. If the person asks to start out throughout, it can restart the above course of
    7. If the person needs to hold on with the end result, it can take this quantity as the primary and ask for the operation, after which comply with as the primary time.

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

    Flowchart (Picture by Creator)

    Defining Operation Capabilities

    To begin with, we’ll outline features that might be referred to as when their corresponding operation image is chosen by the person. We are going to 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 end result.

    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 might be saved as keys, and the identify of the operation, that can be the identify of the operate, might be saved as the worth to that key. We are going to ask the person to decide on an operation, and primarily based on their alternative, the particular operation operate that now we have outlined above might be referred to as.

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

    Asking Person for Enter

    As soon as now we have outlined our features, allow us to now ask the person 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("Decide an operation: ")
    num2 = float(enter("What's the subsequent quantity?: "))

    Discover that now we have transformed the enter numbers to the float kind. Additionally, now we have created the for loop that can iterate over the keys within the operations dictionary now we have 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 person in its full kind. The next code might be used for this goal:

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

    The reply variable will retailer the worth that now we have bought from calling the related operate, in keeping with 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 now we have calculated and displayed the end result, the following step is to test if the person needs to proceed utilizing the calculator by carrying on the end result worth reply onwards or needs to start out the calculator throughout. For this goal, we’ll outline a variable should_accumulate that might be True when the person needs to proceed and might be False when the person doesn’t wish to proceed, moderately it can restart the calculator. The should_accumulate variable might be outlined earlier in our code.

    should_accumulate = True
    
    whereas should_accumulate:
        ...
        alternative = enter(f"Sort 'y' to proceed calculating with {reply}, or kind 'n' to start out a brand new calculation: ")
    
            if alternative == "y":
                num1 = reply
            else:
                should_accumulate = False
                print("n" * 20)
                

    For the reason that should_accumulate variable is True, and now we have added a whereas loop, the code inside the loop will proceed to run, until the person selects ‘n’. When the person selects ‘n’, the calculation won’t carry onwards, however will cease, and we’ll seemingly begin a brand new console by typing 20 strains. However now we wish to restart the calculator, so for this goal, we’ll use a Python operate idea referred to as recursion.

    For the calculator to restart, we’ll outline it as a operate, and it will likely be referred to as after we wish to restart the calculator operate with out carrying on the end result. This might be coded as a recursive operate. Recursion in Python permits a operate to be referred to as inside itself, similar to we’ll 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("Decide an operation: ")
            num2 = float(enter("What's the subsequent quantity?: "))
            reply = operations[operation_symbol](num1, num2)
            print(f"{num1} {operation_symbol} {num2} = {reply}")
    
            alternative = enter(f"Sort 'y' to proceed calculating with {reply}, or kind 'n' to start out a brand new calculation: ")
    
            if alternative == "y":
                num1 = reply
            else:
                should_accumulate = False
                print("n" * 20)
                calculator()

    Discover now we have referred to as the calculator operate contained in the calculator operate 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/Using-Python-to-Build-a-Calculator

    Conclusion

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



    Source link

    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleMy Experiments with NotebookLM for Teaching 
    Next Article Building a Unified Intent Recognition Engine
    ProfitlyAI
    • Website

    Related Posts

    Artificial Intelligence

    TDS Newsletter: How Compelling Data Stories Lead to Better Business Decisions

    November 15, 2025
    Artificial Intelligence

    I Measured Neural Network Training Every 5 Steps for 10,000 Iterations

    November 15, 2025
    Artificial Intelligence

    “The success of an AI product depends on how intuitively users can interact with its capabilities”

    November 14, 2025
    Add A Comment
    Leave A Reply Cancel Reply

    Top Posts

    Transforming Healthcare Documentation: An In-Depth Look at Medical Speech Recognition Technology

    April 5, 2025

    How to Create an LLM Judge That Aligns with Human Labels

    July 21, 2025

    Building A Successful Relationship With Stakeholders

    October 13, 2025

    ChatGPT Feels More Human Than Ever. And It’s Causing Concern

    June 10, 2025

    Alloy App: Features, Benefits, Review and Alternatives

    September 9, 2025
    Categories
    • AI Technology
    • AI Tools & Technologies
    • Artificial Intelligence
    • Latest AI Innovations
    • Latest News
    Most Popular

    The Machine Learning Projects Employers Want to See

    October 31, 2025

    New training approach could help AI agents perform better in uncertain conditions | MIT News

    April 7, 2025

    California’s Bar Exam Was Written by AI And It Was a Total Disaster

    May 1, 2025
    Our Picks

    TDS Newsletter: How Compelling Data Stories Lead to Better Business Decisions

    November 15, 2025

    I Measured Neural Network Training Every 5 Steps for 10,000 Iterations

    November 15, 2025

    “The success of an AI product depends on how intuitively users can interact with its capabilities”

    November 14, 2025
    Categories
    • AI Technology
    • AI Tools & Technologies
    • Artificial Intelligence
    • Latest AI Innovations
    • Latest News
    • Privacy Policy
    • Disclaimer
    • Terms and Conditions
    • About us
    • Contact us
    Copyright © 2025 ProfitlyAI All Rights Reserved.

    Type above and press Enter to search. Press Esc to cancel.