Tuesday, 15 February 2011

Building a calculator in Python -



Building a calculator in Python -

so i'm new python , first thing started working on calculator. mass of code goes towards addressing wrong inputs, trying figure out if there way add/subtract/multiply/divide more 2 numbers. allow user take how many numbers wanted operate , set them calculation. i'm looking possible improvements, more advanced things getting differentiate or integrate functions , stuff. thoughts?

def add(num1, num2): homecoming num1 + num2 def sub(num1, num2): homecoming num1 - num2 def mult(num1, num2): homecoming num1 * num2 def div(num1, num2): homecoming num1 / num2 def main(): operation = raw_input('\n' "what want do? (+, -, *, /): ") if (operation != '+' , operation != '-' , operation != '*' , operation != '/'): print("please come in valid operation") else: while true: try: var1 = float(raw_input("enter num1: ")) var2 = float(raw_input("enter num2: ")) except valueerror: print('\n' "please come in numbers only") go on else: break print('\n' "the reply is:") if(operation == '+'): print(add(var1, var2)) if(operation == '-'): print(sub(var1, var2)) if(operation == '*'): print(mult(var1, var2)) if(operation == '/'): try: print(div(var1, var2)) except zerodivisionerror: print("infinity!") while true: main()

output:

what want do? (+, -, *, /): +

enter num1: 6

enter num2: 4

the reply is:

10.0

what want do? (+, -, *, /): r

please come in valid operation

what want do? (+, -, , /):

enter num1: 1

enter num2: e

please come in numbers only

enter num1: t

please come in numbers only

enter num1: 2.345

enter num2: 4.67

the reply is:

10.95115

what want do? (+, -, *, /): /

enter num1: 4

enter num2: 0

the reply is:

infinity!

what want do? (+, -, *, /):

a couple things at:

for multiple numbers, might take @ varargs, allow set many arguments want function. example:

def add(*args): sum = 0 number in args: sum += number homecoming sum print(add(1, 2, 4, 3)) # prints 10

the * means take passed in after args, , set them in list. makes args list, rather number, , can iterate through it. utilize split function break list of numbers user entered ("1 2 4 3".split()), send them function.

you @ having user input typical mathematical look ("12 + 5 * 4 - 8"), convert postfix notation , parse it, way actual calculators handle type of thing. quite bit more complicated, you'd larn lot python! these links give more info on process: convert postfix evaluate postfix expression

python calculator

No comments:

Post a Comment