#!/usr/bin/env python # coding: utf-8 # # Module 2 # # ## Video 5: Program Flow II # **Python for the Energy Industry** # # ## Conditionals # The `if` statement allows you to specify what to do if a condition is true. Let's say you also want to specify what to do if it is not true: # In[1]: vessel = "ROCINANTE" if vessel == "QUIXOTE": print('Vessel is named QUIXOTE') else: print('Vessel is named something else') # Multiple conditions can be checked for using `elif` and `else`. These must immediately follow an `if` statement. `elif` will run the indented code if the previous condition is not true, but some other specified condition is true. `else` will always run if the previous condition is not true. # In[4]: vessel = "DON" if vessel == "QUIXOTE": print('Vessel is named QUIXOTE') elif vessel == "ROCINANTE": print('Vessel is named ROCINANTE') elif vessel == "DON": print('Vessel is named DON') else: print('Vessel is named something else') # In this example, the first check is if the vessel name is 'QUIXOTE'. As it is not, a second check is done to see if the name is 'ROCINANTE'. This is true, so no further check is done. # ## Loops # # A loop is used to run a chunk of code multiple times. The number of times may be specified in advance, or it may depend on some condition being true, such as in this example of a `while` loop: # In[5]: my_num = 0 while my_num < 5: my_num = my_num + 1 print('my_num =',my_num) print('done') # In[6]: my_num = 1 my_sum = 0 while my_num <= 10: my_sum = my_sum + my_num my_num += 1 print(my_sum) # Here the indented code will run over and over, until the condition that `my_num` is less than 5 is no longer true. Because the indented code adds 1 to `my_num` each time, the code block only runs 5 times. Be careful: if you'd forgotten to change the value of `my_num` within the indented code block, the loop would keep on running until you force it to stop! # ### For Loops # # A `for` loop is a type of loop which iterates over a number of items. For loops are often paired with `range` to iterate over successive numbers: # In[10]: for x in range(3): print(x) # The usefulness of `for` loops will become more clear in the next video. # ### Exercise: # Use a `for` loop to print the sum of all numbers up to and including 100. You should get 5050. # In[ ]: