#!/usr/bin/env python # coding: utf-8 # # Module 2 # # ## Video 4: Program Flow I # **Python for the Energy Industry** # # This is a Jupyter Notebook. A Notebook is composed of cells of Python code which can be run separately. When a cell runs, each line of Python code is run sequentially, and any outputs are displayed below the cell. # In[2]: # A simple example of running a cell my_num = 5 print('my_num =',my_num) my_num = my_num + 2 print('my_num =',my_num) my_num = my_num * 2 print('my_num =',my_num) # ### Understanding Indentation # # In Python, indendation is used to control the order in which lines of code are run. Consider the below: # # ```python # control line with colon: # indented code block line # indented code block line # indented code block line # # code block ends when indent ends # ``` # # The 'control line' determines if, and how many times, the indented code block runs. Once this finishes, the next line of code that is not indented will run. # # This will make more sense when we see some examples. So let's consider the two main types of control line: conditions, and loops. # ### Conditionals # # A conditional control line will allow you to run some lines of code, only if a particular statement is true. The following is an example of the `if` statement. # In[3]: my_num = 2 if my_num == 2: # is my_num equal to 2? my_num = my_num * 3 # if so, multiply it by 3 print('my_num =',my_num) # Here `==` is used to check whether two things are equal. So in this example, the indented code line which multiplies `my_num` by 3, will only run if `my_num` is equal to 2. Note that `==` is different from `=`, the 'assignment' operator, which sets the value of a variable. # # `==` is an example of a 'comparative' operator. Other common comparative operators in Python are: # # | operator | meaning | # |---|---| # | `<` | less than | # | `>` | greater than | # | `<=` | less than or equal to | # | `>=` | greater than or equal to | # | `!=` | not equal to | # ### Exercise # # Modify the above code block to: # # a) Change the initial value of my_num # b) Change the operator used in the control line # # Check that the printed output changes as you would expect. # In[ ]: