# Brief Introduction to Python

## Contents

# 2. Brief Introduction to Python#

As mentioned, this book is designed to help understand and solve thermodynamics problems using Python, and for this a small introduction to Python is necessary. This introduction will cover the basics in terms of it’s installation, writing some basic code, evaluation, and creating figures. No prior Python experience is necessary and this textbook will take a hands-on approach - you will learn more advanced skills as we progress throughout the chapters. This is not intended to be a comprehensive Python course however, and for a more thorough overview of Python I recommend other, more dedicated resources. Specifically for data analysis I reccommend the book “Python for Data Analysis” by Wes McKinney [McKinney, 2022].

## 2.1. Installing Python#

Download Python from https://www.anaconda.com/ (“Anaconda Distribution”). This distribution includes many useful applications but most commonly we will use JupyterLab, which is a notebook style Python editor that allows you to evaluate Python code line by line or cell by cell, rather than an entire file. This is useful for a variety of reasons, as we will see shortly. In fact, this entire textbook is written in a Jupyter Notebook! You can format text in cells in a markdown language if markdown is selected or edit Python code if the cell is indicated as code. These indicators are options in a drop down menu at the top of the notebook.

## 2.2. Opening a Notebook#

Jupyter notebook files have a .ipny extension. To open a Jupyter Notebook, first locate the Anadonda Navigator that was installed on your computer. Then on the Home screen, locate the JupyterLab application and click “Launch”. This will open JupyterLab in your preferred browser. Click the + icon on the top left and select the notebook option - this will open a Jupyter Notbook as a new tab within JupyterLab. You should see a blank cell at the top which is where you can enter your Python code or markdown content. Pressing shift-enter (or the play icon) will evaluate the contents in that cell and only that cell, whether it is Python code or markdown. You can add a new cell with the + icon within the notebook (not the one originally clicked on the far left of the screen that creates a new file). It is up to you when you create new cells versus adding content to an existing cell in a new line, but in general I find it is good practice to break content into small chunks, similar to writing paragraphs. The nice thing about individual cells is that only the content in that cell is updated when you evaluate it, and therefore you can update variables or other content without having to compile the rest of your code, which can result in more efficient evaluation. Don’t worry if this is overwhelming at this point, we will try some simple examples below!

## 2.3. Simple Examples Demonstrating Cell Evaluation#

Go ahead and open a new notebook and type the content below from the first line (the second line is output that is generated) into your notebook and press shift-enter. You should see the same output of 4 generated in your notebook.

```
2+2
```

```
4
```

Now, lets define a variable x, as x = 5. Enter this into your own notebook in a new cell and press shift-enter.

```
x=5
```

Then lets add another cell that calculates the value of 10 times x. Enter as below and press shift-enter. The result of 50 as below should appear in the output.

```
10*x
```

```
50
```

Now, go back to the second cell where x is defined and change the value from 5 to 10, or whatever you would like. Evaluate the cell and notice that the output below the cell with 10 times x didn’t change. To update its output you would need to evaluate that cell again by pressing shift-enter. It should be apparant that the tradiational top-down heirarchy of coding doesn’t apply here when working with notebooks - it is the evaluation order of cells that matters.

## 2.4. Importing Packages and Calling Functions#

In Python, there are several powerful computing packages commonly used that should be declared within your code in order to use their functions. For example, some of the more popular computational packages useful for engineering include numpy, scipy, matplotlib and pandas, among others. These must be installed on your computer, either manually using a package installer (e.g. pip installer https://pip.pypa.io/en/stable/), or are installed by default with many Python distributions, including the Anaconda Distribution that we have used. For example, if we want to utilize the numpy package we can use the import function and say

```
import numpy as np
```

which allows us to call the numpy package simply by typing np. We don’t need to install anything because the numpy package comes by default with Anaconda. If we wish to use numpy package to calculate the cosine of an angle, for example we would first need to call it by typing np followed by a period and then the function contained within the package we wish to utilize, in this case cos, and the value within it (in this case the numerical value pi which is also called using the numpy package as \(np.pi\)) contained within parenthesis. For example,

```
np.cos(np.pi)
```

```
-1.0
```

## 2.5. Declaring Functions#

Functions are declared (i.e., created) in Python by defining them using \(def\) followed by the proposed function name, and parenthesis that include any variables the function is dependent on, followed by a colon. The body of the function is then started on a new, indented line and the value that is returned by the function must be declared at the end using \(return\) For example, if we wish to define a function y that depends on x and is a linear line with slope m and intercept y we would write

```
def y(x):
return m*x+b
```

and to evaluate the function, for example at x=3, we would simply call it by defining m and b to equal some arbitrary constants and typing the following.

```
m,b = 2,5
y(3)
```

```
11
```

## 2.6. Lists, Arrays and Indexing#

Lists and Arrays in Python are both data structures that allow indexing and iterating, and they can be sometimes used interchangeably but in other cases one is preferred. A list is a built-in data structure native to Python, while an array is a data structure that is part of the numpy computing package. In general arrays are more suited for numerical operations compared to lists. We can create a list and convert it to an array, or vice versa. To create a list you insert the values separated by a comma, all contained within brackets. For example,

```
testlist = [1,2,3]
print(testlist)
```

```
[1, 2, 3]
```

To convert it to an array we call the \(numpy\) package and include the list name inside parenthesis of the function \(np.array\).

```
import numpy as np
testarray = np.array(testlist)
print(testarray)
```

```
[1 2 3]
```

We can then convert from an array back to a list by using the function, \(list\).

```
testlist = list(testarray)
print(testlist)
```

```
[1, 2, 3]
```

If an array is inserted as a parameter within a function, it will be evaluated at each index of the array. This will not work if a list is inserted however and would need to be done in an iterative manner, for example using a for loop.

To conveniently create an array of x values to be evaluated within a function we can use the numpy function arange. To use this we will have to call the numpy package and arange by \(np.arange\) and within this function we include the starting value, ending value and spacing, all separated by commas. For example, to create an array called x_vals from 1 to 10 with a spacing of 1 we type.

```
x_vals=np.arange(1,11,1)
print(x_vals)
```

```
[ 1 2 3 4 5 6 7 8 9 10]
```

Then we can evaluate the function \(y\) we defined above at each index of the array *x_vals* by inserting this array into the function, like below.

```
print(y(x_vals))
```

```
[ 7 9 11 13 15 17 19 21 23 25]
```

Indexing of lists and arrays in Python is straightforward. However, it is important to note that the first index starts with 0, the second 1, and so on. To recall an indexed part of a list or array we follow the name of the list or array with \([index]\). An example using a list is below.

```
testlist = [10,23,43]
testlist[1]
```

```
23
```

And below is an example using an array.

```
testlist = [10,23,43]
testarray = np.array(testlist)
testarray[1]
```

```
23
```

Finally, a range of indexes can be selected by following the list or array with \([index1:index2]\). See below

```
testarray=np.arange(1,11,1)
testarray[2:7]
```

```
array([3, 4, 5, 6, 7])
```

## 2.7. Plotting Using Matplotlib#

To plot functions or lists/arrays of data, we can use the package Matplotlib. To use this package, it is as simple importing the function \(matplotlib.pyplot\) and creating lists or arrays of x and y values to be plotted.

For example, lets import \(matplotlib\) and plot the function \(y\) we have defined above between x = 0 and 5, keeping m and b equal to 2 and 5, respectively.

```
import matplotlib.pyplot as plt # this package allows us to plot functions
plt.plot(x_vals,y(x_vals))
plt.xlabel('x')
plt.ylabel('y(x)')
plt.show()#needed to display plot
```

Notice that the definitions from prior cells still apply in new cells. For example, we didn’t need to redefine *x_vals* since it was already created above. If we update a definition in a different cell, for example, *x_vals*, and then evaluate any cells afterwards that contain it they will be updated - regardless if they appear above or below. For example, to update the plot to vary from x = 1 to 100 we could redefine \(x_vals=np.arange(1,101,1)\) anywhere, and then evaluate the above plotting cell again to update it. This is one advantage of notebook style evaluation compared to traditional compilers that evaluate all lines of code sequentially.

## 2.8. Cantera Package#

Cantera is a Python package that we will use extensively to evaluate properties of real substances. This will be discussed throughout several sections later, but for now we just need to get the package installed. As mentionened, the anaconda distribution that we downloaded comes with many useful data analysis and computation packages but it does not come with Cantera. Using this link https://cantera.org/install/conda-install.html, install the Cantera module using instructions under Option 1: Create a new environment for Cantera. Copy and paste the instructions in the cmd .exe prompt found on your Anaconda Navigator home screen. Once installed you will have to work from the environment you created, called ct-env, if you want to use Cantera. To operate from this environment click the “Application on” tab at the top of your Anaconda Navigator home screen and then install Jupyter Notebook in this environment.

Now we are ready to use Python and Cantera using Jupyter! We are going to evaluate a few simple properties of H_{2}O just to confirm this is working as expected.

```
import cantera as ct
species1 = ct.Water()# define species1 as water
species1() #show properties of species 1
```

```
water:
temperature 300 K
pressure 1.0132e+05 Pa
density 996.63 kg/m^3
mean mol. weight 18.016 kg/kmol
vapor fraction 0
phase of matter liquid
1 kg 1 kmol
--------------- ---------------
enthalpy -1.5858e+07 -2.857e+08 J
internal energy -1.5858e+07 -2.857e+08 J
entropy 3913.2 70500 J/K
Gibbs function -1.7032e+07 -3.0685e+08 J
heat capacity c_p 4180.8 75321 J/K
heat capacity c_v 4131 74424 J/K
```

The output should show the default temperature and pressure which are 300 K and 1.0132e+05 Pa, the corresponding density, molecular weight, vapor fraction and phase. Details of these properties will all be discussed in Section 4 Evaluation of Properties. Below that are listed even more properties including enthalpy, internal energy, entropy, Gibbs function, and two forms of heat capacity - again, the meaning of these properties is not important at this point and will be dicussed in later sections. These properties are shown on a per kg or per kmol basis.

We can change the temperature and pressure at which corresponding properties are evaluated by calling \(species1\), followed by \(TP\). For example,

```
species1.TP = 273.15+30, 100000 #Redefine Temperature in K and Pressure in Pa at State 1
species1() #show properties of species 1
```

```
water:
temperature 303.15 K
pressure 1e+05 Pa
density 995.73 kg/m^3
mean mol. weight 18.016 kg/kmol
vapor fraction 0
phase of matter liquid
1 kg 1 kmol
--------------- ---------------
enthalpy -1.5845e+07 -2.8546e+08 J
internal energy -1.5845e+07 -2.8546e+08 J
entropy 3956.8 71286 J/K
Gibbs function -1.7044e+07 -3.0707e+08 J
heat capacity c_p 4178.6 75282 J/K
heat capacity c_v 4116.1 74156 J/K
```

Similar strategies can be used to set other combinations of properties as discussed later when we formally introduce Cantera to evaluate properties of real substances in Section 4 Evaluation of Properties.