Tonmoy
Tonmoy

Reputation: 11

Syntax error defining a simple function

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

Upvotes: 0

Views: 59

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121992

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.

Upvotes: 3

Related Questions