Skip to content

Latest commit

 

History

History
70 lines (49 loc) · 1.98 KB

File metadata and controls

70 lines (49 loc) · 1.98 KB

12.1 Simple Calculator

The task

Create a simple calculator. That will be able to take user input of two numbers and the operation the user wants to perform.

Solution strategy

Create a bunch of functions to perform add, subtract, multiply, division or modulo.

Then take two numbers from the user and the operation he/she wants to perform. Either +,-,*,/ or %.

Then call the appropriate function based on the operation.

Think for a few minutes and try it yourself first.

The solution

defadd(num1, num2): returnnum1+num2defsubtract(num1, num2): returnnum1-num2defmultiply(num1, num2): returnnum1*num2defdivide(num1, num2): returnnum1/num2defmodulo(num1, num2): returnnum1%num2# Take input from the usernum1=int(input("Enter first number: ")) operation=input("What you want to do(+, -, *, /, %):") num2=int(input("Enter second number: ")) result=0ifoperation=='+': result=add(num1,num2) elifoperation=='-': result=subtract(num1,num2) elifoperation=='*': result=multiply(num1,num2) elifoperation=='/': result=divide(num1,num2) elifoperation=='%': result=modulo(num1,num2) else: print("Please enter: +, -, *, / or %") print(num1, operation, num2, '=', result)

Try it on Programming Hero

How it works

You saw five functions to add, subtracts, etc. Those are easy.

Then we are taking user inputs. Three inputs. They are easy too.

Then we have if-elif-else. And based on the operation, we call the right method to perform the task.

That’s it.

  Next Page  

tags: programming-heropythonpython3problem-solvingprogrammingcoding-challengeinterviewlearn-pythonpython-tutorialprogramming-exercisesprogramming-challengesprogramming-fundamentalsprogramming-contestpython-coding-challengespython-problem-solving

close