HW01: Introduction to Python#
The first homework problem is solved with Python. You’ll complete the below labeled actions. Look for places where an Action is required. The following topics are covered:
install Python
help, print, type
variable names
operators
import packages
introduction to numpy
introduction to matplotlib
The following code is to display YouTube videos and URL links in the Notebook. There is no need to modify this code.
# function to display YouTube videos and external web-pages
import numpy as np
from IPython.core.display import display, HTML
def video(key):
display(HTML('<iframe width="560" height="315" src="https://www.youtube.com/embed/'+key+'" \
frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>'))
/var/folders/6d/1jr2w1qx1rnd2nkndlq4hc700000gn/T/ipykernel_60954/2426028648.py:3: DeprecationWarning: Importing display from IPython.core.display is deprecated since IPython 7.14, please import from IPython display
from IPython.core.display import display, HTML
Problem 1#
Install Python if you have a laptop computer. If not, then skip this step and use the CAEDM computer that already has Anaconda and Jupyter notebook. You can also use Google Colab.
Action 1a: Download and install Anaconda (Jupyter Notebook) from https://www.anaconda.com/distribution/
video('LrMOrMb8-3s')
/Users/clintguymon/opt/anaconda3/envs/jupiterbook/lib/python3.9/site-packages/IPython/core/display.py:431: UserWarning: Consider using IPython.display.IFrame instead
warnings.warn("Consider using IPython.display.IFrame instead")
Getting Started#
Some of the most useful things for getting started are to use print()
, help()
, and know how to search for answers online with Google, Bard, or ChatGPT and in forums such as StackOverflow.
Action 1b: Change 'my message'
to a different text message.
print('my message')
my message
Action 1c: Show the help documentation for the max
function instead of the print
function. Based on the help, use the max
function to find the highest value of two numbers: 5
and 2
.
help(print)
Help on built-in function print in module builtins:
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
Variable Names#
There are three types of basic variables in Python. These are:
string (e.g. ‘banana’)
integer (e.g. 2)
float (e.g. 3.1415)
A variable name must begin with a letter or underscore but not with a number or other special characters. A variable name must not have a space and lowercase or uppercase are permitted.
Action 1d: Correct the following errors in the variable names.
# correct the variable name errors
1var = 1
my Var = 2
test!Var = 3
#myVar = 4
Cell In[5], line 2
1var = 1
^
SyntaxError: invalid syntax
Variable Types#
Every variable is stored as an object that is shown with the type
function:
myVar = 2
print(type(myVar))
Produces <class ‘int’>, meaning that myVar
is an integer type. Values can be converted to a different type such as with:
int
: convert to an integerfloat
: convert to a floating point number with a decimal valuestr
: convert to a string (sequence of characters)
The type of the variable can change (mutable) in Python.
Action 1e: Print the variable value and type for x
, y
, and z
. Explain why x
is 46 and not 10.
x = int('2'+'3')*2
y = x - 10.0
z = str(4.0)
# print the values of x, y, and z
# determine the type for x, y, and z
# explain why x is equal to 46, not 10
Functions of the str Object#
In addition to a value, the str
object has useful functions such as lower
and upper
to convert to lower or upper case, respectively.
myVar = 'my name'
print(myVar.upper())
The result is 'MY NAME'
.
Action 1f: Insert your name and then convert and print it in lower case with the str.lower() function.
myStr = 'Your Name'
With numpy, there are a number of other functions including sin
, cos
, exp
, log
, sqrt
, sum
, max
, min
, abs
, round
, floor
, ceil
, etc.
# for example you can take the exponential of 5:
print(np.exp(5))
You can also create you’re own functions such as the volume of a sphere with radius r
:
def sphereVolume(r):
return (4/3)*np.pi*r**3
#for a sphere with radius 5, the volume is:
print(sphereVolume(5))
523.5987755982989
Action 1g: Create a function for the volume of a cylinder with radius r
and height h
. Then print the result of calling that function with r=2
and h=5
.
Operators#
Operators are used to transform, compare, join, substract, etc. Below is a list of operators in descending order of precedence when there are no parenthesis to guide the precedence.
Operator |
Description |
---|---|
** |
Exponent |
*, /, //, % |
Multiplication, Division, Floor division, Modulus |
+, - |
Addition, Subtraction |
<= < > >= |
Comparison |
= %= /= //= -= += *= **= |
Assignment |
is, is not |
Identity |
in, not in |
Membership |
not, or, and |
Logical |
Action 1h: Use the operator list to determine whether \(5^5\) is greater than \(2^{10}\).
# modify to determine whether 5^5 is greater than 2^10
5 == 2
Classes#
You’ll use classes with dot notation throughout this course and throughout your time here using python for scientific computing. The following code is an example of a class that you’ll use in this course.
import param
class chair(param.Parameterized):
legs = param.Integer(4, bounds=(1, 4))
color = param.ObjectSelector(default="red", objects=["red", "green", "blue"])
mychair = chair(legs=3, color="blue") #instance of the chair class
print(f'My chair has {mychair.legs} legs and is {mychair.color}.') #print the attributes of mychair
My chair has 3 legs and is blue.
Action 1g: Define a class called molecule that has the following attributes: name, formula, and weight. The name and formula should be strings and the weight should be a float. Use the param package to automatically instantiate the object upon calling . Create an instance of the class called water that has the name ‘water’, the formula ‘H2O’, and the weight 18.01528. Print the name of the molecule. You can use the example code in the lecture to help you (or any other source) but please make sure you do all of the typing (no copy and paste).
Problem #2#
Packages#
Python capabilities are extended with many useful packages. A few of the packages that we’ll use in this class are:
NumPy (Numerical Python) as a base numerical package
Matplotlib for creating charts and visualizing data
SciPy (Scientific Python) as a base scientific package
Pandas data analysis library
Gekko for simulation and optimization
Anaconda comes with many of the packages built-in but there are sometimes packages that you’ll need to add. Below is a video tutorial on managing the packages in Python.
video('Z_Kxg-EYvxM')
You can import a package with import **package** as **pk**
where **package**
is the package name and **pk**
is the abbreviated name.
Action 2a: Import the numpy
package as np
(shortened name) and get help on the np.linspace
function.
Action 2b: Use np.linspace
to define 20 equally spaced values between \(0\) and \(2\,\pi\). Name the variable x
and use the built-in np.pi
constant for \(\pi\).
Action 2c: Use np.sin
to calculate a new variable y
as \(y=2\,\sin{\left(\frac{x}{2}\right)}\).
Action 2d: Import the matplotlib.pyplot
package as plt
(shortened name) and show the help on the plt.plot
function. To show plots in an IPython notebook, the additional code %matplotlib inline
is required.
Action 2e: Create a plot of x
and y
with the plt.plot
function. Add an x-label with plt.xlabel
and a y-label with plt.ylabel
. If you are not using an IPython notebook, include plt.show()
to display the plot. You can also include it in an IPython notebook but it won’t have any effect.
Problem #3#
Create an account on Kaggle. Go to the Learn section, find the Python course, and complete the first lesson called “Hello,Python”.
Record here that you have completed this exercise and record the date and time in this cell.
Problem #4#
Action 4: Describe which of the world problems highlighted in the Motivation lecture that most interest you in helping to solve.
Problem #5#
Read the Deseret News article about energy (DN Energy Article)
Credit to Dr. John Hedengren for many of these problems (see also APMonitor.com)