I am making a calculator which executes only a certain number of operations, if anything else is entered it prints a reminder message. But during that process an name error occurs, just after it prints'a'. where am i going wrong?
if Operation == '+':
c = a + b
elif Operation == '-':
c = a - b
elif Operation == '*':
c = a * b
elif Operation == '/':
c = a / b
else:
print('Read the Instructions again, dimmwit')
print('Your answer is', c)
print('Thanks! Have a great time!')
And pls give a few suggestions on how should i improve my code.
You really should also post the particular NameError you're getting, and the traceback. (And your full code.)
Anyway, the problem is you're not initializing c
to anything, so when control falls out of the "insult the user" else
, trying to print c
can't happen.
Give c
some value in all cases, then check whether you actually did an operation:
c = None
if Operation == "+":
c = a + b
elif Operation == "-":
c = a - b
elif Operation == "*":
c = a * b
elif Operation == "/":
c = a / b
else:
print("Read the Instructions again, dimmwit")
if c is not None:
print("Your answer is", c)
print("Thanks! Have a great time!")
Better still, do the computation in a function of its own, and output things to the user elsewhere:
def compute(operation, a, b):
if operation == "+":
return a + b
elif operation == "-":
return a - b
elif operation == "*":
return a * b
elif operation == "/":
return a / b
return None
c = compute(operation, a, b)
if c is not None:
print("Your answer is", c)
print("Thanks! Have a great time!")
else:
print("Please read the instructions again.")