Python Forum

Full Version: How to Loop my calculator input
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello guys, I created a addition and subtraction calculator and I am wondering how to get the calculator to keep looping where it keeps asking for an input and then carrying out the right operation. Right now, it takes the inputs, prints the result and then the application stops.

Here is the code:


a = float(input("what operation are you trying to : Select 1 for addition 2 for subtraction "))

while a >=3:
print("Wrong input")
a = float(input(" Please enter the right input: Select 1 for addition 2 for subtraction "))
if a < 3:
print("Thank you for your correct input ")

b = float(input("please enter the first number:"))
c = float(input("please enter the second number"))
d = float(input("Please enter the number you want for the operation "))
e = b + c
f = b - c

if d == 1:
print (e)

if d == 2:
print (f)


Thanks in advance!
can you try below to see if that helps,Also later when used division and other operators, better we use try and except blocks too to catch the exceptions,

class calc():
	def calc_add(self,a,b):
		return a+b;
	def calc_sub(self,a,b):
		return a-b;

print("welcome i am calc")
while True:
	line=int(input("choose 1 : add  and 2 : sub   and 0 to exit  -->"))
	if line == 1:
		a=int(input("enter value a: "))
		b=int(input("enter value b: "))
		x=calc()
		print('result is : ',x.calc_add(a,b))
	elif line == 2:
		a=int(input("enter value a: "))
		b=int(input("enter value b: "))
		x=calc()
		print('result is : ',x.calc_sub(a,b))
	elif line == 0:
		break
	elif line > 2:
		print("wrong input given, please rety:")
    else:
		print("you have given negative number, please retry")
Best Regards,
Sandeep

GANGA SANDEEP KUMAR
Thank Sandeep for sharing script. I made a little change to improve the code: can deal with cases where line < 1, and can calculate values which are not integer.

Best Regards,

class calc():
    def calc_add(self,a,b):
        return a+b;
    def calc_sub(self,a,b):
        return a-b;

print("welcome I am calc")
line=1
while True:
    line=int(input("choose 1: add and 2: sub and 0 to exit -->"))
    if line == 1:
        a=float(input("enter value a: "))
        b=float(input("enter value b: "))
        x=calc()
        print('result is :',x.calc_add(a,b))
    elif line == 2:
        a=float(input("enter value a: "))
        b=float(input("enter value b: "))
        x=calc()
        print('result is :',x.calc_sub(a,b))
    elif line == 0:
        break
    else:
        print("wrong input given, please retry:")