I have a simple function to do simple math operations. If I call this from another script using import, I get no output. If I remove def function, everything is working fine. What’s the problem with defining this function? I’m new to Python.
def calci(a, op, b):
if op == '+':
c = a + b
elif op == '-':
c = a-b
elif op == '*':
c= a*b
elif op =='/':
if(b == 0):
print('can\'t divide')
c = a/b
print('value is',c)
return c
result = calci(12,'+', 12)
print(result)
Do you want to return the result to the calling function or print it? The only path through your program that results in a
returnis division, and when you do this you’ll never reach theprintstatement.If you want to do both, you should dedent the part:
…to the level of the
ifandelifstatements. Don’t forget to remove your testing code (result = calci(...)etc).The reason is that once your code hits a
returnstatement, that’s it for the function — nothing else in it will be executed (not quite true, there is an exception handling mechanism called afinallyblock which is an exception to this, but that’s not an issue here).Added: since you want to just print it, remove the
returnstatement and dedent theprintstatement.