views:

63

answers:

4

Here's a simple function to do simple math operations, when i call this from other program using import, output i get is none. When 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)  nter code here
+3  A: 

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.

detly
i want to print it, not send it to function, when it din't work i tried to return value!!
abhilashm86
yes at the end indent was mising, so it printed NONE, now its working.......
abhilashm86
+3  A: 

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
Michael Mrozek
now return too is working, thanks....
abhilashm86
+1  A: 

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
Xanify
+1  A: 

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)
SHiNKiROU