Just started teaching myself how to code, however I've run into a bit of annoying Python syntax problem. Every time I try to copy the examples from my textbook directly into IDLE, I get a syntax error. Even after retyping it, trying different indentations, and so on. I apologize this is so basic! Also is there a way to "recall" the above problem code after it's been entered? Thanks!
>>> def f(x, y, z):
return x + y + z
result = f(1, 2, 3)
print(result)
--OR--
def f(x, y, z):
return x + y + z
result = f(1, 2, 3)
print(result)
I get "syntaxerror: invalid syntax" (on the 'result' line.)
Expected answer is 6.
You're typing the code directly into IDLE's interactive window (a.k.a. REPL - read-execute-print loop) window.
In this mode, every statement you type is executed immediately. A quirk of this mode is that Python needs an extra blank line after a function definition, so that it knows the function definition is finished, and it can execute it.
So, your IDLE input needs to look like this (including IDLE's prompt):
>>> def f(x, y, z):
return x + y + z
>>> result = f(1, 2, 3)
>>> print(result)
6
Alternatively, you can use IDLE more like a traditional IDE, where you write the code in a file, execute the file, edit the file, repeat.
To do this, go to File
-> New File
, and type all your code into the window that pops up. You can execute the code with Run
-> Run Module
, and of course you can save and load this file as you'd expect.