0

Why this simple function is not working in python 2.7?

>>> def a(b,h):
...     return b*h/2
... a(3,4)
  File "<stdin>", line 3
    a(3,4)
    ^
SyntaxError: invalid syntax
>>> 
2
  • this is not going to give you the answer you expect even once you fix the syntax errors Commented Dec 8, 2015 at 18:25
  • 1
    @JoranBeasley: sure it is. The answer is 6, which is correct. Commented Dec 8, 2015 at 18:32

1 Answer 1

3

In the interactive interpreter, you'll need to add a blank line to close off the statement before the function is defined:

>>> def a(b,h):
...     return b*h/2
...
>>>

Once you do, a new >>> prompt appears and you can enter the a(3,4) call.

From the Python reference documentation on Interactive input:

Note that a (top-level) compound statement must be followed by a blank line in interactive mode; this is needed to help the parser detect the end of the input.

Note that you may run into issues with integer division here; in Python 2 if both operands to the / division operator are integers, you'll get an integer result. See How can I force division to be floating point? Division keeps rounding down to 0 for work-arounds.

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

3 Comments

although unless there is a from __future__ import ... this still wont give OP expected answer
@JoranBeasley: 3 * 4 / 2 works just fine, because 12 is divisible by 2.
:P ok so it works for some cases (including the one the OP posted :P )

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.