1

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.

0

1 Answer 1

4

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.

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

2 Comments

I know you imply this, but as the OP is confused it may be good to be completely explicit: you only need to put a blank link after the function definition when running Python in interactive mode (Idle or a console prompt). If (as you will usually do) you create a .py file and run that, it is entirely your choice whether or not to use a blank line.
What the hell? Man, I am already enjoying coding.... Simple hack, that's all that was needed. Thanks guys!! Now, back to the drawing board :)

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.