!!! Blocks This is __Exercise 2__ of the [Micro Python Tutorial]. In Python, a block is a group of statements that belong together, forming the body of a function, loop, class or other structure. A block is defined by an initial line followed by the contents of the block indented four characters. As an example, a {{for}} block sets up a loop: %%filename main.py %% %%python for i in range(0,5): print(i) %% Notice that the contents of the {{for}} block are indented four characters. This causes the contents of the block to be executed five times, printing the value of the index variable ("i") each time. !! The try-except-finally Block 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. 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). %%filename main.py %% %%python try: print('hello world.') # remember to indent the insides of your blocks by 4 characters! 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.') %% 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}}). %%filename main.py %% %%python try: print('hello world.') except Exception as ex: print('an error occurred: {}'.format(ex)) finally: print('complete.') %% ---- __Previous:__ [MicroPython Tutorial Exercise 1|MicroPythonTutorialExercise01]: main.py \\ __Next:__ [MicroPython Tutorial Exercise 3|MicroPythonTutorialExercise03]: functions