-1

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.

Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
  • 1
    There's nothing wrong with your syntax, and AFAICT both your blocks are identical? – Blorgbeard Jun 26 '19 at 00:46
  • 2
    Ah, ok - when you type it into IDLE, make sure you type a blank line after the function definition. After `return x + y + z`, press enter twice, until you get a new `>>>` prompt – Blorgbeard Jun 26 '19 at 00:47
  • Alternatively, `File -> New File`, type all your code in there and then hit F5 to run it. This also allows you to save and load the text (your "recall" question). – Blorgbeard Jun 26 '19 at 00:48
  • 1
    The required blank line to terminate compound statements is required by the python, whenever it is in interactive mode. not by IDLE. – Terry Jan Reedy Jun 26 '19 at 22:42

2 Answers2

0

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.

Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
-1

Python use indent to identify the code block. So make sure you have right indent for you code block.

todaynowork
  • 976
  • 8
  • 12