#calcu using if else
print("PYTHON CALCULATOR.\n")
while True:
try:
no1 = int(input("Please enter first integer: "))
no2 = int(input("Please enter second integer: "))
break
except ValueError:
print("Only numbers can be inputed.\n")
chc = input("Please enter an operation[+ , - , / , *]: ")
def add():
result = no1 + no2
print("Result: ",result)
def subt():
result = no1 - no2
print("Result: ",result)
def multi():
result = no1 * no2
print("Result: ",result)
def div():
result = no1 / no2
print("Result: ",result)
if chc == '+':
add()
elif chc == '-':
subt()
elif chc == '*':
multi()
elif chc == '/':
div()
else:
print("Wrong Input. Try again.")
Looks like your indentation is wrong, the second half of your code is not inside the loop
You’ve got this to ensure you get two integers:
while True:
try:
no1 = int(input("Please enter first integer: "))
no2 = int(input("Please enter second integer: "))
break
except ValueError:
print("Only numbers can be inputed.\n")
which is kind of neat.
But then you run through your checks below, which are ok in their way. But
if you want this to loop again (to ask for another pair of numbers) you
need an outer loop, eg:
while True: # the outer loop
while True: # the loop just for 2 good inputs
try:
no1 = int(input("Please enter first integer: "))
no2 = int(input("Please enter second integer: "))
break
except ValueError:
print("Only numbers can be inputed.\n")
... all your other code, indented inside the outer loop ...
BTW, we tend to define functions just once before their use, so I’d put
add the def add()
etc functions before the loops.
Inside your functions the values no1 and no2 cannot be used.
They can, actually. Closures.
Change the function like this:
def add(no1, no2):
but this is good advice anyway.
Yep, I know… so deleted the post.