-1

Why does this code give me a syntax error in idle? enter image description here if I use python online, which was correct. enter image description here

I was expecting an output like the second photo. What is the problem and how can I fix it?

3
  • 1
    Don't post images of code, errors or data. Post the text in the question. See How to Ask Commented Nov 29, 2023 at 19:56
  • @TangentiallyPerpendicular - In this particular case images are necessary to demonstrate the difference between two environments. Commented Nov 29, 2023 at 20:01
  • @PM77-1 No image is needed. See my answer with proper quoted text as T.P. requested. Commented Dec 1, 2023 at 16:48

1 Answer 1

1

This issue is NOT about IDLE. Rather, it is about interactive mode versus batch (file) mode. In an interactive REPR (Read-Execute_PRint*) loop, the interpreter reads, executes, and prints the result of one command/statement/expression at a time. Submitting more than one at a time is usually an error. In batch mode, the interpreter reads multiple execution units at once.

In Python, execution units can span more than one physical line. Here is Python's standard REPL mode.

>>> def f():
...   print(1)
... f()
  File "<stdin>", line 3
    f()
    ^
SyntaxError: invalid syntax

In Python, the end of a compound statememt (one with a header terminated by :) is signaled by a blank line. See this tutorial section. Adding a blank line to the above results in:

>>> def f():
...   print(1)
...
>>> f()
1

The online python used has a batch mode editor (and submit file mechanism) and therefore did not have the interactive mode start '>>>' and continuation '...' prompts. Thus, no blank line is required.

* I am aware that the 'E' is usually taken to mean 'Eval' (from 'evaluate an expression', as in Lisp) rather that 'Execute', but the latter is more appropriate for statements.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.