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.
Because of this:
else:
print('Read the Instructions again, dimmwit')
It is possible that by the time
print('Your answer is', c)
is reached, there is no c
defined if that else
route is taken.
If you make this a function, such as:
def print_result(operation, a, b):
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')
return
print('Your answer is', c)
print('Thanks! Have a great time!')
Then you can stop early with the return
, instead of attempting to print an answer c
that is never computed.
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.")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.