This page (revision-21) was last changed on 2025-07-30 13:27 by Murray Altheim

This page was created on 2025-07-30 02:24 by Murray Altheim

Only authorized users are allowed to rename pages.

Only authorized users are allowed to delete pages.

Page revision history

Version Date Modified Size Author Changes ... Change note
21 2025-07-30 13:27 826 bytes Murray Altheim to previous

Page References

Incoming links Outgoing links

Version management

Difference between version and

At line 15 removed one line
In Python there is a {{try-except-finally}} structure called a "compound statement" consisting of three separate __blocks__, which is ideal for a main.py file.
At line 17 changed one line
In the below example, there is a {{try}} block, followed by an {{except}} block, followed by a {{finally}} block. A {{try}} block must be followed by an {{except}} block and/or a {{finally}} block (you must have one of them).
!! The REPL
At line 19 changed 3 lines
%%filename main.py %%
%%python
try:
__REPL__ stands for ''Read, Evaluate, Print, Loop''. The REPL is how you interact with the Python Interpreter.
At line 23 changed one line
print('hello world.') # remember to indent the insides of your blocks by 4 characters!
Unlike running a file containing Python code, in the REPL you can type commands and instantly see the output
printed out. You can also use the REPL to print out help for methods and objects in Python, list out what
methods are available, and much more.
At line 25 changed 7 lines
except Exception:
# this block is executed if there is an exception (error)
print('an error occurred.')
finally:
# this is always executed, no matter what
print('complete.')
%%
We'll use the REPL to execute our main.py program. Depending on how you are using Python, you can access the REPL
on a command line, using a command line application (like mpremote or rshell), or within the user interface of a
Python IDE (Integrated Development Environment) like Thonny.
At line 33 changed one line
If you want to use the exception to print out an error message you need to assign it to a variable (in this case, we've used {{ex}}).
No matter how you get access to the REPL, once you see its command line you can type commands, hitting {{{RETURN}}}
to execute them.
At line 35 changed 3 lines
%%filename main.py %%
%%python
try:
On Linux or the Terminal in Mac OS:
At line 39 changed 6 lines
print('hello world.')
except Exception as ex:
print('an error occurred: {}'.format(ex))
finally:
print('complete.')
%%repl ► python3
Python 3.10.12 (main, May 27 2025, 17:12:29) [GCC 11.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
At line 39 added one line
Or using rshell, let's execute our main.py script:
At line 41 added 13 lines
%%repl
/pyboard> repl
Entering REPL. Use Control-X to exit.
>
MicroPython v1.25.0 on 2025-04-15; Raspberry Pi Pico with RP2040
Type "help()" for more information.
>>>
>>> import main
hello world.
hello again.
>>>
%%