5

In this program is an intentional syntax error

import random
random.seed(16)

while True:
    n = random.randrange(1,101)
    print(n)
    if n < 30: break

if n==20:
    break

Run with !python test.py on google colab yields as expected

  File "test.py", line 10
    break
    ^
SyntaxError: 'break' outside loop

But run as a juypter notebook cell on google colab gives the output

47
61
62
37
54
30
58
1
  File "<ipython-input-43-35a4321b0145>", line 10
    break
    ^
SyntaxError: 'break' outside loop

In juypter notebook the program runs until leaving the while loop. My understanding was that the cell would be saved in a temporary file and executed using the standard python interpreter. Why is the execution different?

15
  • Put the whole while and if n == 20 part inside an if True block. You'll notice how Jupyter breaks up the execution into blocks.
    – 9769953
    Aug 28, 2021 at 18:58
  • 2
    To me, this seems to me that CPython on the command line works on file basis, while Jupyter does some extra parsing and works on compound statement basis.
    – 9769953
    Aug 28, 2021 at 19:07
  • @9769953 You are correct. I am wrong. It does not work in Python, Jupyter Lab or Juno. Something fishy. Aug 28, 2021 at 19:13
  • I wouldn't call it fishy: it is another way of parsing the code (perhaps undocumented; or perhaps according to the Python standard, parsing is left to the Python implementation). In fact, it may make sense, considering cells in Jupyter are often written as single compound statements (no, not meant as a contradiction).
    – 9769953
    Aug 28, 2021 at 19:17
  • 1
    I reproduced it with Google Colab. I believe the answer lies on the implementation. Digging on how Colab works will shine the answer. Aug 28, 2021 at 19:26

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy