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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With