Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python Program to Calculate Gross Salary of a Person
Next article icon

Smart calculator in Python

Last Updated : 11 Jan, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Problem – This smart calculator works on the text statement also. The user need not provide algebraic expression always. It fetches the word form the command (given by the user) and then formulates the expression.
Examples: 

Input  : Hi calculator plz find the lcm of 4 and 8.   Output : 8   Input  : Hi smart plz find the  multiplication of 3 and 9.  Output : 27   Input  : Hi smart plz end the program.  Output : Thanks for enjoy with me.

 
Code : Python code for smart calculation 
 
 

Python3




# main python proghram
response=['Welcome to smart calculator','My name is MONTY',
          'Thanks for enjoy with me ','Sorry ,this is  beyond my ability']
 
# fetching tokens from the text command
def extract_from_text(text):
    l=[]
    for t in text.split(' '):
        try:
            l.append(float(t))
        except ValueError:
            pass
    return l
 
# calculating LCM
def lcm(a,b):
    L=a if a>b else b
    while L<=a*b:
        if L%a==0 and L%b==0:
            return L
        L+=1
 
# calculating HCF
def hcf(a,b):
    H=a if a<b else b
    while H>=1:
        if a%H==0 and b%H==0:
            return H
        H-=1
 
# Addition
def add(a,b):
    return a+b
 
# Subtraction
def sub(a,b):
    return a-b
 
# Multiplication
def mul(a,b):
    return a*b
 
# Division
def div(a,b):
    return a/b
 
# Remainder
def mod(a,b):
    return a%b
 
# Response to command
# printing - "Thanks for enjoy with me" on exit
def end():
    print(response[2])
    input('press enter key to exit')
    exit()
  
def myname():
    print(response[1])
def sorry():
    print(response[3])
  
# Operations - performed on the basis of text tokens
operations={'ADD':add,'PLUS':add,'SUM':add,'ADDITION':add,
            'SUB':sub,'SUBTRACT':sub, 'MINUS':sub,
            'DIFFERENCE':sub,'LCM':lcm,'HCF':hcf,
            'PRODUCT':mul, 'MULTIPLY':mul,'MULTIPLICATION':mul,
            'DIVISION':div,'MOD':mod,'REMAINDER'
            :mod,'MODULAS':mod}
 
# commands
commands={'NAME':myname,'EXIT':end,'END':end,'CLOSE':end}
          
print('--------------'+response[0]+'------------')
print('--------------'+response[1]+'--------------------')
  
  
while True:
    print()
    text=input('enter your queries:  ')
    for word in text.split(' '):
        if word.upper() in operations.keys():
            try:
                l = extract_from_text(text)
                r = operations[word.upper()] (l[0],l[1])
                print(r)
            except:
                print('something went wrong going plz enter again !!')
            finally:
                      break
        elif word.upper() in commands.keys():
                      commands[word.upper()]()
                      break
    else:        
        sorry()
 
 

Output: 

--------------Welcome to smart calculator------------ --------------My name is MONTY--------------------   enter your queries:  tell me the hcf of 4 and 8 4.0   enter your queries:  hi plz tell me 7 + 8 Sorry ,this is  beyond my ability   enter your queries:  pls add 7 and 8 15.0


Next Article
Python Program to Calculate Gross Salary of a Person

M

Mateshwari Verma
Improve
Article Tags :
  • Python
  • Python Programs
Practice Tags :
  • python

Similar Reads

  • Make a Simple Calculator - Python
    In this article, we will create a simple calculator that can perform basic arithmetic operations like addition, subtraction, multiplication and division. We will explore two implementations for the same: Command-Line CalculatorGUI-Based Calculator using TkinterCommand-Line CalculatorThis version of
    3 min read
  • Program to create grade calculator in Python
    Given different scored marks of students. We need to find a Grade Calculator in Python. The test score is an average of the respective marks scored in assignments, tests, and lab work. The final test score is assigned using the below formula. 10% of marks scored from submission of Assignments 70% of
    4 min read
  • Python Program to calculate Profit Or Loss
    Given the Cost Price(CP) and Selling Price(SP) of a product. The task is to calculate the Profit or Loss.Example: Input: CP = 1500, SP = 2000Output: 500 ProfitInput: CP = 3125, SP = 1125Output: 2000 LossFormula: Profit = (Selling Price - Cost Price) Loss = (Cost Price - Selling Price) Program to cal
    1 min read
  • Python program to calculate square of a given number
    The task of calculating the square of a number in Python involves determining the result of multiplying a number by itself. For example, given the number 4, its square is 16 because 4 × 4 = 16. Using ** operatorexponentiation operator (**) is the most direct and optimized way to compute powers. Sinc
    1 min read
  • Python Program to Calculate Gross Salary of a Person
    The task of calculating the Gross Salary of a Person in Python involves taking the basic salary and grade as input, applying the necessary calculations for salary components and displaying the final salary. The gross salary formula: Gross Salary = Basic Salary + HRA + DA + Allowance - PF Where: HRA
    3 min read
  • Python - Operation to each element in list
    Given a list, there are often when performing a specific operation on each element is necessary. While using loops is a straightforward approach, Python provides several concise and efficient methods to achieve this. In this article, we will explore different operations for each element in the list.
    3 min read
  • Factorial of a Number - Python
    The factorial of a number is the product of all positive integers less than or equal to that number. For example, the factorial of 5 (denoted as 5!) is 5 × 4 × 3 × 2 × 1 = 120. In Python, we can calculate the factorial of a number using various methods, such as loops, recursion, built-in functions,
    4 min read
  • Python String Input Output
    In Python, input and output operations are fundamental for interacting with users and displaying results. The input() function is used to gather input from the user and the print() function is used to display output. Input operations in PythonPython’s input() function allows us to get data from the
    3 min read
  • Interesting Facts About Python
    Python is a high-level, general-purpose programming language that is widely used for web development, data analysis, artificial intelligence and more. It was created by Guido van Rossum and first released in 1991. Python's primary focus is on simplicity and readability, making it one of the most acc
    7 min read
  • Output of Python Program | Set 1
    Predict the output of following python programs: Program 1: [GFGTABS] Python r = lambda q: q * 2 s = lambda q: q * 3 x = 2 x = r(x) x = s(x) x = r(x) print (x) [/GFGTABS]Output: 24Explanation : In the above program r and s are lambda functions or anonymous functions and q is the argument to both of
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences