0

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)

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

i want to print it, not send it to function, when it din't work i tried to return value!!
3

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

Comments

1

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

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.