Hi all i am learning python and here in below code i am trying to making a simple calculator very basic but i need people of stackoverflow and help me guide me its working properly but my main concern is "return operator.get(operator_sign)(val1,val2)" this piece of code which is working fine but my question is, is this proper way or anything else should i do. And my another question is i need suggestions from all of you that how can i improve myself in code as i have heard be a smart coder we are not doing essay writing here.
from art import logo
print(logo)
def add(a,b):
return a b
def sub(a,b):
return a-b
def mul(a,b):
return a*b
def div(a,b):
return a/b
def operation(val1,val2,operator_sign):
return operator.get(operator_sign)(val1,val2)
operator = {
" ": add,
"-": sub,
"*": mul,
"/": div,
}
val1 = int(input('Please provide your first input value:\n'))
val2 = int(input('Please provide your second input value:\n'))
operator_sign = input('What operation do you wish to perform\n" " - Addition\n"-" - Subtraction\n"*" - Multiplication\n"/" - Division\n')
print(operation(val1,val2,operator_sign))
CodePudding user response:
First of all, take a look at this link. It will help you in further developing and help other people to better read and understand your code.
You code works fine, but in python you can do calculator much easier:
>>> result = eval(input("Input: "))
Input: 1 1 / 2 - 4 * 2
>>> print(f"Result = {result}")
Result = -6.5
P.S. There are a lot of ways to implement calculator. But the main thing, you should think about, is handling user's input. Each time user input something, you often want to check if input is legit. Minimal example:
>>> try:
eval(input("Input: "))
except:
print("Sorry, your input can't be proccessed by my calculator :(")
Input: 1 plus 2
Sorry, your input can't be proccessed by my calculator :(
CodePudding user response:
This is fine. If you are running python 3.10 , you could turn it into a Switch/Match case which can allow you to add more complex operations with less code:
from art import logo
print(logo)
def peformOperation(val1,val2,operator):
match operator:
case " ":
return(val1 val2)
case "-":
return(val1-val2)
case "*":
return(val1*val2)
case "/":
return(val1/val2)
val1 = int(input('Please provide your first input value:\n'))
val2 = int(input('Please provide your second input value:\n'))
operator_sign = input('What operation do you wish to perform\n" " - Addition\n"-" - Subtraction\n"*" - Multiplication\n"/" - Division\n')
print(peformOperation(val1,val2,operator_sign))