• About
  • Advertise
  • Privacy & Policy
  • Contact
Thursday, January 1, 2026
  • Login
  • Home
    • Home – Layout 1
    • Home – Layout 2
    • Home – Layout 3
    • Home – Layout 4
    • Home – Layout 5
    • Home – Layout 6
  • News
    • All
    • Business
    • Politics
    • Science
    • World
    Hillary Clinton in white pantsuit for Trump inauguration

    Hillary Clinton in white pantsuit for Trump inauguration

    Amazon has 143 billion reasons to keep adding more perks to Prime

    Amazon has 143 billion reasons to keep adding more perks to Prime

    Shooting More than 40 Years of New York’s Halloween Parade

    Shooting More than 40 Years of New York’s Halloween Parade

    These Are the 5 Big Tech Stories to Watch in 2017

    These Are the 5 Big Tech Stories to Watch in 2017

    Why Millennials Need to Save Twice as Much as Boomers Did

    Why Millennials Need to Save Twice as Much as Boomers Did

    Doctors take inspiration from online dating to build organ transplant AI

    Doctors take inspiration from online dating to build organ transplant AI

    Trending Tags

    • Trump Inauguration
    • United Stated
    • White House
    • Market Stories
    • Election Results
  • Tech
    • All
    • Apps
    • Gadget
    • Mobile
    • Startup
    The Legend of Zelda: Breath of the Wild gameplay on the Nintendo Switch

    The Legend of Zelda: Breath of the Wild gameplay on the Nintendo Switch

    Shadow Tactics: Blades of the Shogun Review

    Shadow Tactics: Blades of the Shogun Review

    macOS Sierra review: Mac users get a modest update this year

    macOS Sierra review: Mac users get a modest update this year

    Hands on: Samsung Galaxy A5 2017 review

    Hands on: Samsung Galaxy A5 2017 review

    The Last Guardian Playstation 4 Game review

    The Last Guardian Playstation 4 Game review

    These Are the 5 Big Tech Stories to Watch in 2017

    These Are the 5 Big Tech Stories to Watch in 2017

    Trending Tags

    • Nintendo Switch
    • CES 2017
    • Playstation 4 Pro
    • Mark Zuckerberg
  • Entertainment
    • All
    • Gaming
    • Movie
    • Music
    • Sports
    The Legend of Zelda: Breath of the Wild gameplay on the Nintendo Switch

    The Legend of Zelda: Breath of the Wild gameplay on the Nintendo Switch

    macOS Sierra review: Mac users get a modest update this year

    macOS Sierra review: Mac users get a modest update this year

    Hands on: Samsung Galaxy A5 2017 review

    Hands on: Samsung Galaxy A5 2017 review

    Heroes of the Storm Global Championship 2017 starts tomorrow, here’s what you need to know

    Heroes of the Storm Global Championship 2017 starts tomorrow, here’s what you need to know

    Harnessing the power of VR with Power Rangers and Snapdragon 835

    Harnessing the power of VR with Power Rangers and Snapdragon 835

    So you want to be a startup investor? Here are things you should know

    So you want to be a startup investor? Here are things you should know

  • Lifestyle
    • All
    • Fashion
    • Food
    • Health
    • Travel
    Shooting More than 40 Years of New York’s Halloween Parade

    Shooting More than 40 Years of New York’s Halloween Parade

    Heroes of the Storm Global Championship 2017 starts tomorrow, here’s what you need to know

    Heroes of the Storm Global Championship 2017 starts tomorrow, here’s what you need to know

    Why Millennials Need to Save Twice as Much as Boomers Did

    Why Millennials Need to Save Twice as Much as Boomers Did

    Doctors take inspiration from online dating to build organ transplant AI

    Doctors take inspiration from online dating to build organ transplant AI

    How couples can solve lighting disagreements for good

    How couples can solve lighting disagreements for good

    Ducati launch: Lorenzo and Dovizioso’s Desmosedici

    Ducati launch: Lorenzo and Dovizioso’s Desmosedici

    Trending Tags

    • Golden Globes
    • Game of Thrones
    • MotoGP 2017
    • eSports
    • Fashion Week
  • Review
    The Legend of Zelda: Breath of the Wild gameplay on the Nintendo Switch

    The Legend of Zelda: Breath of the Wild gameplay on the Nintendo Switch

    Shadow Tactics: Blades of the Shogun Review

    Shadow Tactics: Blades of the Shogun Review

    macOS Sierra review: Mac users get a modest update this year

    macOS Sierra review: Mac users get a modest update this year

    Hands on: Samsung Galaxy A5 2017 review

    Hands on: Samsung Galaxy A5 2017 review

    The Last Guardian Playstation 4 Game review

    The Last Guardian Playstation 4 Game review

    Intel Core i7-7700K ‘Kaby Lake’ review

    Intel Core i7-7700K ‘Kaby Lake’ review

No Result
View All Result
Ai News
Advertisement
  • Home
    • Home – Layout 1
    • Home – Layout 2
    • Home – Layout 3
    • Home – Layout 4
    • Home – Layout 5
    • Home – Layout 6
  • News
    • All
    • Business
    • Politics
    • Science
    • World
    Hillary Clinton in white pantsuit for Trump inauguration

    Hillary Clinton in white pantsuit for Trump inauguration

    Amazon has 143 billion reasons to keep adding more perks to Prime

    Amazon has 143 billion reasons to keep adding more perks to Prime

    Shooting More than 40 Years of New York’s Halloween Parade

    Shooting More than 40 Years of New York’s Halloween Parade

    These Are the 5 Big Tech Stories to Watch in 2017

    These Are the 5 Big Tech Stories to Watch in 2017

    Why Millennials Need to Save Twice as Much as Boomers Did

    Why Millennials Need to Save Twice as Much as Boomers Did

    Doctors take inspiration from online dating to build organ transplant AI

    Doctors take inspiration from online dating to build organ transplant AI

    Trending Tags

    • Trump Inauguration
    • United Stated
    • White House
    • Market Stories
    • Election Results
  • Tech
    • All
    • Apps
    • Gadget
    • Mobile
    • Startup
    The Legend of Zelda: Breath of the Wild gameplay on the Nintendo Switch

    The Legend of Zelda: Breath of the Wild gameplay on the Nintendo Switch

    Shadow Tactics: Blades of the Shogun Review

    Shadow Tactics: Blades of the Shogun Review

    macOS Sierra review: Mac users get a modest update this year

    macOS Sierra review: Mac users get a modest update this year

    Hands on: Samsung Galaxy A5 2017 review

    Hands on: Samsung Galaxy A5 2017 review

    The Last Guardian Playstation 4 Game review

    The Last Guardian Playstation 4 Game review

    These Are the 5 Big Tech Stories to Watch in 2017

    These Are the 5 Big Tech Stories to Watch in 2017

    Trending Tags

    • Nintendo Switch
    • CES 2017
    • Playstation 4 Pro
    • Mark Zuckerberg
  • Entertainment
    • All
    • Gaming
    • Movie
    • Music
    • Sports
    The Legend of Zelda: Breath of the Wild gameplay on the Nintendo Switch

    The Legend of Zelda: Breath of the Wild gameplay on the Nintendo Switch

    macOS Sierra review: Mac users get a modest update this year

    macOS Sierra review: Mac users get a modest update this year

    Hands on: Samsung Galaxy A5 2017 review

    Hands on: Samsung Galaxy A5 2017 review

    Heroes of the Storm Global Championship 2017 starts tomorrow, here’s what you need to know

    Heroes of the Storm Global Championship 2017 starts tomorrow, here’s what you need to know

    Harnessing the power of VR with Power Rangers and Snapdragon 835

    Harnessing the power of VR with Power Rangers and Snapdragon 835

    So you want to be a startup investor? Here are things you should know

    So you want to be a startup investor? Here are things you should know

  • Lifestyle
    • All
    • Fashion
    • Food
    • Health
    • Travel
    Shooting More than 40 Years of New York’s Halloween Parade

    Shooting More than 40 Years of New York’s Halloween Parade

    Heroes of the Storm Global Championship 2017 starts tomorrow, here’s what you need to know

    Heroes of the Storm Global Championship 2017 starts tomorrow, here’s what you need to know

    Why Millennials Need to Save Twice as Much as Boomers Did

    Why Millennials Need to Save Twice as Much as Boomers Did

    Doctors take inspiration from online dating to build organ transplant AI

    Doctors take inspiration from online dating to build organ transplant AI

    How couples can solve lighting disagreements for good

    How couples can solve lighting disagreements for good

    Ducati launch: Lorenzo and Dovizioso’s Desmosedici

    Ducati launch: Lorenzo and Dovizioso’s Desmosedici

    Trending Tags

    • Golden Globes
    • Game of Thrones
    • MotoGP 2017
    • eSports
    • Fashion Week
  • Review
    The Legend of Zelda: Breath of the Wild gameplay on the Nintendo Switch

    The Legend of Zelda: Breath of the Wild gameplay on the Nintendo Switch

    Shadow Tactics: Blades of the Shogun Review

    Shadow Tactics: Blades of the Shogun Review

    macOS Sierra review: Mac users get a modest update this year

    macOS Sierra review: Mac users get a modest update this year

    Hands on: Samsung Galaxy A5 2017 review

    Hands on: Samsung Galaxy A5 2017 review

    The Last Guardian Playstation 4 Game review

    The Last Guardian Playstation 4 Game review

    Intel Core i7-7700K ‘Kaby Lake’ review

    Intel Core i7-7700K ‘Kaby Lake’ review

No Result
View All Result
Ai News
No Result
View All Result
Home Machine Learning

Using Python to Build a Calculator

AiNEWS2025 by AiNEWS2025
2025-09-17
in Machine Learning
0
Using Python to Build a Calculator
0
SHARES
0
VIEWS
Share on FacebookShare on Twitter


Calculators date back to the 17th century, with the first calculator created in the form of a mechanical device. Over time, these calculators evolved so that more people could use them. It was in the 1960s, that the first electronic calculator came into being, and as time went on, the calculator was integrated into our computers and now mobiles.

Either physical or digital, we live in a time where each of us has used a calculator. Whether we are calculating rent, totalling the bill, or finding the final percentage of our kids’ results, we all have taken help from the calculator.

Let’s utilize Python basics, including functions, conditional statements, dictionaries, and loops, to create our version of a calculator.

Working of our Calculator

Our calculator will work as follows:

  1. It will ask the user for a number
  2. It will then ask the user for the operation
  3. It will ask the user for the second number
  4. It will perform its calculations and print the output
  5. It will ask the user if they want to carry on with this number (like our physical calculator) or start all over
  6. If the user asks to start all over, it will restart the above process
  7. If the user wants to carry on with the result, it will take this number as the first and ask for the operation, and then follow as the first time.

Let us construct the above thought process into a flowchart for better understanding:

Flowchart (Image by Author)

Defining Operation Functions

First of all, we will define functions that will be called when their corresponding operation symbol is selected by the user. We will define functions add for addition, subtract for subtraction, multiply for multiplication, and divide for division. These functions will take the two numbers as their input parameters, and perform the selected operation on them, and return the 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

Creating a Dictionary of Operations

Let us also create a dictionary of operations. The operation symbols will be stored as keys, and the name of the operation, that is also the name of the function, will be stored as the value to that key. We will ask the user to choose an operation, and based on their choice, the specific operation function that we have defined above will be called.

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

Asking User for Input

Once we have defined our functions, let us now ask the user for their first number num1, their selected operation operation_symbol, and their second number num2:

num1 = float(input("What is the first number?: "))
for symbol in operations:
            print(symbol)
operation_symbol = input("Pick an operation: ")
num2 = float(input("What is the next number?: "))

Notice that we have converted the input numbers to the float type. Also, we have created the for loop that will iterate over the keys in the operations dictionary we have defined earlier on, and print each operation symbol.

Calculating and Displaying the Answer

Next, is to calculate the answer and print it out to the user in its complete form. The following code will be used for this purpose:

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

The answer variable will store the value that we have got from calling the relevant function, according to the operation symbol selected. We have used an f-string to properly format the output statement.

Check Calculator Continuity with the While Loop

Now that we have calculated and displayed the result, the next step is to check if the user wants to continue using the calculator by carrying on the result value answer onwards or wants to start the calculator all over. For this purpose, we will define a variable should_accumulate that will be True when the user wants to continue and will be False when the user does not want to continue, rather it will restart the calculator. The should_accumulate variable will be defined earlier in our code.

should_accumulate = True

while should_accumulate:
    ...
    choice = input(f"Type 'y' to continue calculating with {answer}, or type 'n' to start a new calculation: ")

        if choice == "y":
            num1 = answer
        else:
            should_accumulate = False
            print("\n" * 20)
            

Since the should_accumulate variable is True, and we have added a while loop, the code within the loop will continue to run, unless the user selects ‘n’. When the user selects ‘n’, the calculation will not carry onwards, but will stop, and we will seemingly start a new console by typing 20 lines. But now we want to restart the calculator, so for this purpose, we will use a Python function concept called recursion.

For the calculator to restart, we will define it as a function, and it will be called when we want to restart the calculator function without carrying on the result. This will be coded as a recursive function. Recursion in Python allows a function to be called within itself, just like we will do below:

def calculator():
    should_accumulate = True
    num1 = float(input("What is the first number?: "))

    while should_accumulate:
        for symbol in operations:
            print(symbol)
        operation_symbol = input("Pick an operation: ")
        num2 = float(input("What is the next number?: "))
        answer = operations[operation_symbol](num1, num2)
        print(f"{num1} {operation_symbol} {num2} = {answer}")

        choice = input(f"Type 'y' to continue calculating with {answer}, or type 'n' to start a new calculation: ")

        if choice == "y":
            num1 = answer
        else:
            should_accumulate = False
            print("\n" * 20)
            calculator()

Notice we have called the calculator function inside the calculator function itself. For the code to run for the first time, we need to call it outside.

Check out this link to access the complete code: https://github.com/MahnoorJaved98/Using-Python-to-Build-a-Calculator

Conclusion

In this short tutorial, we have successfully learned how to build a calculator in Python, with the ability to perform the basic 4 operations on addition, subtraction, multiplication and division. We have accomplished this using our basic knowledge of functions, loops, and recursive functions.

Source link

#Python #Build #Calculator

Tags: CalculatorcodingmathProjectsPython
Previous Post

A record supply load won’t reach the International Space Station as scheduled

Next Post

The looming crackdown on AI companionship

AiNEWS2025

AiNEWS2025

Next Post
The looming crackdown on AI companionship

The looming crackdown on AI companionship

Stay Connected test

  • 23.9k Followers
  • 99 Subscribers
  • Trending
  • Comments
  • Latest
A tiny new open source AI model performs as well as powerful big ones

A tiny new open source AI model performs as well as powerful big ones

0
Water Cooler Small Talk: The Birthday Paradox 🎂🎉 | by Maria Mouschoutzi, PhD | Sep, 2024

Water Cooler Small Talk: The Birthday Paradox 🎂🎉 | by Maria Mouschoutzi, PhD | Sep, 2024

0
Ghost of Yōtei: The acclaimed Ghost of Tsushima is getting a sequel

Ghost of Yōtei: The acclaimed Ghost of Tsushima is getting a sequel

0
Best Headphones for Working Out (2024): Bose, Shokz, JLab

Best Headphones for Working Out (2024): Bose, Shokz, JLab

0
MIT engineers design an aerial microrobot that can fly as fast as a bumblebee

MIT engineers design an aerial microrobot that can fly as fast as a bumblebee

2025-12-31
Production-Ready LLMs Made Simple with the NeMo Agent Toolkit

Production-Ready LLMs Made Simple with the NeMo Agent Toolkit

2025-12-31
Here we go again: Retiring coal plant forced to stay open by Trump Admin

Here we go again: Retiring coal plant forced to stay open by Trump Admin

2025-12-31
Why inventing new emotions feels so good

Why inventing new emotions feels so good

2025-12-31

Recent News

MIT engineers design an aerial microrobot that can fly as fast as a bumblebee

MIT engineers design an aerial microrobot that can fly as fast as a bumblebee

2025-12-31
Production-Ready LLMs Made Simple with the NeMo Agent Toolkit

Production-Ready LLMs Made Simple with the NeMo Agent Toolkit

2025-12-31
Here we go again: Retiring coal plant forced to stay open by Trump Admin

Here we go again: Retiring coal plant forced to stay open by Trump Admin

2025-12-31
Why inventing new emotions feels so good

Why inventing new emotions feels so good

2025-12-31
Footer logo

We bring you the best Premium WordPress Themes that perfect for news, magazine, personal blog, etc. Check our landing page for details.

Follow Us

Browse by Category

  • AI & Cloud Computing
  • AI & Cybersecurity
  • AI & Sentiment Analysis
  • AI Applications
  • AI Ethics
  • AI Future Predictions
  • AI in Education
  • AI in Fintech
  • AI in Gaming
  • AI in Healthcare
  • AI in Startups
  • AI Innovations
  • AI News
  • AI Research
  • AI Tools & Automation
  • Apps
  • AR/VR & AI
  • Business
  • Deep Learning
  • Emerging Technologies
  • Entertainment
  • Fashion
  • Food
  • Gadget
  • Gaming
  • Health
  • Lifestyle
  • Machine Learning
  • Mobile
  • Movie
  • Music
  • News
  • Politics
  • Review
  • Robotics & Smart Systems
  • Science
  • Sports
  • Startup
  • Tech
  • Travel
  • World

Recent News

MIT engineers design an aerial microrobot that can fly as fast as a bumblebee

MIT engineers design an aerial microrobot that can fly as fast as a bumblebee

2025-12-31
Production-Ready LLMs Made Simple with the NeMo Agent Toolkit

Production-Ready LLMs Made Simple with the NeMo Agent Toolkit

2025-12-31
  • About
  • Advertise
  • Privacy & Policy
  • Contact

© 2026 JNews - Premium WordPress news & magazine theme by Jegtheme.

Welcome Back!

Login to your account below

Forgotten Password?

Retrieve your password

Please enter your username or email address to reset your password.

Log In
No Result
View All Result

© 2026 JNews - Premium WordPress news & magazine theme by Jegtheme.