Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid syntax error in Python

I'm starting Comp Sci courses in Uni this coming fall (starting with zero programming knowledge), so I'm just starting to play around programming. I'm following a book and tried copy-pasting some code - but it doesn't work. Here's what I tried:

>>> def function(x):
    return x+2
function(2)
SyntaxError: invalid syntax

The word "function" was highlighted. I'm confused because the very same example is used in the book and it appears to work but then I get that error on my end. What's going on here?

like image 976
Colly Avatar asked Dec 20 '22 17:12

Colly


1 Answers

You need to separate the function definition from its execution. Also, Python is sensitive to whitespace at the beginning of lines. Try this (exactly):

def function(x):
    return x+2
function(2)

or, in one line (which you should not do; see the style guidelines):

def function(x): return x+2; function(2)

or, in the Python shell:

>>> def function(x):
    return x+2

>>> function(2)
4

Note the blank line between the function definition and its use. After you define the function, hit enter once to get the prompt back.

like image 64
dbn Avatar answered Dec 29 '22 18:12

dbn