python simple function error?
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开发者_如何学Python 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 return
is division, and when you do this you'll never reach the print
statement.
If you want to do both, you should dedent the part:
print('value is',c)
return c
...to the level of the if
and elif
statements. Don't forget to remove your testing code (result = calci(...)
etc).
The reason is that once your code hits a return
statement, that's it for the function — nothing else in it will be executed (not quite true, there is an exception handling mechanism called a finally
block which is an exception to this, but that's not an issue here).
Added: since you want to just print it, remove the return
statement and dedent the print
statement.
Your indentation at the end of the function appears to be wrong; the print
and return c
are only happening if op == '/'
, and you're only assigning to c
if b == 0
. The end should be:
elif op =='/':
if(b == 0):
print('can\'t divide') # You should probably return here instead of falling through to the assignment
c = a/b
print('value is',c)
return c
Your function only returns if op=='/'.
Remove a couple of tabs from those two lines and it'll work.
i.e.
def calci(a, op, b):
...
print('value is',c)
return c
The indentation of the return part is incorrect, it should be lower-one-level. (This is so hard to describe... a flaw of Python's indentation syntax)
Here is the correct code:
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')
return 0
c = a/b
print('value is',c)
return c
result = calci(12,'+', 12)
print(result)
精彩评论