简体   繁体   中英

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?

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.

I'm assuming you meant to put Python in the title. Python has interesting syntax rules in that it actually counts white space as meaningful when parsing the program. What I mean is that having extra space, newlines, or tabs, etc. actually changes the meaning of the program. Double check the book example and make sure you have the exact same (tabs, new lines, and all) syntax written. It may look closer to this:

def f(x):
    return x + 2

note the new line and tab. To call this function, on a separate line say:

f(5)

or replace 5 with whatever parameter you want.

edit:

so the full script should be:

def f(x):
    return x + 2

f(2)

Try this:

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

In python, indentations are important. They are the {} of the python world.

You actually do not need to add extra whitespace before function(5) because python knows not to include it in the function definition because it is not indented. It is still good practice to add the extra blank line, but it is not strictly necessary.

This is for the users using Python 2.6.6 and IDLE 2.6.6.

Since Python interpreter is very much sensitive to whitespace and indentations, we need to separate the function declaration from the execution.

What you must be doing:

>>> def square(input):
    output=input*input
    return output
print square(5)

Output: SyntaxError: invalid syntax

Correct way to do it:

>>> def square(input):
    output=input*input
    return output

>>> print square(3)
9

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM