fr_muses
fr_muses

Reputation: 1473

Unable to Define Basic Functions in Python

I have just started to learn coding with Python. I was following instructions from the tutorials on Coursera and I am encountering an issue with defining the basic functions in Python.

My code is as follows:

>>> 
>>> def f(x):
    return x*2
f(3)
SyntaxError: invalid syntax
>>> 
>>> 

I am using the following Python package:

Python 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 01:25:11) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin

The same code displayed on the tutorial seems to be working fine wherein Python 3.2.3 is being used. Appreciate some advice.

Upvotes: 1

Views: 254

Answers (1)

Volatility
Volatility

Reputation: 32300

The IDLE Shell can only parse a single block of code at a time. The function definition and the function call are considered as different "blocks", so you need to separate them, by pressing Enter again after the function definition.

>>> def f(x):
    return x*2

>>> f(3)
6

Note that a "block" in this context is basically either just a stand-alone line of code, or any code that is indented and preceded by a line ending with a colon (:).

Like @Duncan mentioned, the blank line is only required in the interactive shell - it needs to know if there's still more to the block or you're done and you want the code to run. In a normal .py file, blank lines don't matter as the interpreter will know what to do because the code has already been written in it's entirety.

Upvotes: 4

Related Questions