0% found this document useful (0 votes)
90 views

Department of Civil Engineering: DR Barbara Turnbull H21POR

This document provides instructions for a Python workshop. It begins by outlining the key learning objectives of being able to access Python, update it and related packages, execute simple math functions, and write and run a "Hello World" script. The document then discusses Python being open source software and why it is useful for data analysis and solving numerical problems in engineering. Step-by-step instructions are provided for installing Python and getting started, including using the Jupyter notebook interface. Examples are given of simple math operations and using print statements to display output.

Uploaded by

san htet aung
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
90 views

Department of Civil Engineering: DR Barbara Turnbull H21POR

This document provides instructions for a Python workshop. It begins by outlining the key learning objectives of being able to access Python, update it and related packages, execute simple math functions, and write and run a "Hello World" script. The document then discusses Python being open source software and why it is useful for data analysis and solving numerical problems in engineering. Step-by-step instructions are provided for installing Python and getting started, including using the Jupyter notebook interface. Examples are given of simple math operations and using print statements to display output.

Uploaded by

san htet aung
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Dr Barbara Turnbull H21POR

Department of Civil Engineering

B4 Python 1/4 Environmental Fluid Mechanics

After this session you should

• Be able to access python on your laptop, installing it if necessary

• Update python; install a package manager or a suitable text editor and set your preferred editor
as the default for python scripts

• Execute simple mathematical functions interactively in python at the command line prompt

• Write and execute a python script that displays Hello, World!

Python is an OPEN SOURCE code. This means that it is freely available to anyone to download and
use. The disadvantage is that you need to be responsible for managing it on your computer, ensuring
you have the right toolboxes (‘modules’), text editors or interfaces and keeping things up to date. But
there are many advantages including the cost, versatility, lack of platform dependence and continual
development by the community. There is a large amount of online help and resource for you to start
using python in a wide range of situations. In this workshop we will use freely available materials to
educate ourselves, in the way that you will use python or similar programmes in the future.

Consider this workshop as self-learning, with support from us. This is just a first step in starting to
build up both your confidence and a library of scripts to get you going in tackling engineering problems
numerically. We can’t teach you python in 16 hours, but we will try and teach you enough to recognise
how to teach yourself from this point on and to work out the problems you find.

Who uses python?

Software developers (Google, Wikipedia, Reddit, Games Workshop), Research scientists (CERN, the UK
Met Office). You can also get python plug ins for specialist tools such as CAD and ArcGIS. Raspberry
Pi uses python.

Why would I need to use python?

There are two main reasons that python is likely to be useful to you as an engineer:

• Data analysis: Excel is great for manipulating simple data and producing a graph quickly. However,
it is not very efficient and the analysis you can do is quite limited (in terms of platform dependence,

1
file size, data types; there are only 17 179 869 184 cells - and that is just when they are empty - in
an excel spreadsheet!). Collecting, analysing and visualising data - especially from varied sources
- is best done with a scientific programming language with visualisation capability such as python
or MatLab.

• Solving numerical problems: You learn in maths how to solve equations that describe physical
situations. However, typically, you have to make assumptions to make the equations simple enough
to actually be able to solve them. You can use numerical methods to e.g. integrate equations
that you cannot integrate analytically, and thereby increase the scope of problems you can solve.

In addition, software is becoming increasingly important in civil engineering - as a management tool and
in design. Using it is relatively straightforward, but understanding what it produces and the validity of
that takes knowledge of how the software is constructed. It is good to develop your understanding of
this, and maybe even be the people who develop new software for civil engineers in the future.

How do I get started?

We will use python 2.7 - which is the last stable version to be released before python 3. Python 3 is
still under some development and not all modules are ready.

• Method 1 (for confident students):

– Install/update python from an installer package at


https://www.python.org/downloads/release/python-2711/

– Install/update a text editor - recommend Notepad++ for Windows, or textwrangler for Mac
https://notepad-plus-plus.org/download/v7.3.2.html
https://itunes.apple.com/gb/app/textwrangler/id404010395?mt=12

– For Mac, follow instructions at


http://www.macworld.co.uk/how-to/mac/coding-with-python-on-mac-3635912/
- you will need to install xcode and command line tools if you do not already have these.

– For Windows, follow instructions


http://docs.python-guide.org/en/latest/starting/install/win/
- you will need to ensure python is in your path. To find out if python is in your path type
‘python’ at the windows command line. If the message
‘python’ is not recognized as an internal or external command, operable program
or batch file. shows, you will need to do the following:

2
∗ Navigate to the system properties pane by searching ’environment’ and selecting edit
the system environment variable or alternatively: Control panel > System and security
> System > Advanced system settings.

∗ Click Environment Variables to open the environment variables pane.

∗ Under System variables select path and click edit.

∗ Add the directory where Python is installed e.g. ‘C:\Python27;” to the end of the variable
value string.

∗ Reopen CMD.exe and type ‘python’ and check if python has been successfully added to
the path. The python version should be displayed. Type ‘exit()’ or press ctrl-z to exit
the python interpreter.

– For both. To add on a web notebook (recommended for starters), you will need to use the
pip installer system (or similar). From you terminal/dos command prompt run
$ pip install --upgrade pip
to install and update your pip system and then to install the jupyter notebook
$ pip install jupyter

– If you cannot get method 1 to work, use method 2.

• Method 2 (good for starters): Use a package manager such as Anaconda, to install and update
your python and modules within it.
https://www.continuum.io/downloads
So long as you unpack and install in the right directory (i.e. your python working directory),
everything should go painlessly into the correct places and you do not need to worry about adding
in additional packages etc.. The disadvantage is that it takes up a lot more space on your drive.

If you want to use a nice web interface for your python (good for starters), now follow the
instructions here to get the jupyter notebook.
http://jupyter.readthedocs.io/en/latest/install.html

For both methods, be careful where you are installing and running things. I suggest you make a python
directory in your home space and unpack, install and run your programmes there (not in the downloads
folder!).

How do I use python?

Find a good book, such as:


http://greenteapress.com/thinkpython/thinkpython.pdf

3
In your terminal/dos window navigate to your python folder and type
$ python
and you should see the 3 chevrons (the ‘prompt’) indicating that you are in the interpreter.

EXERCISE A
Try some simple maths:
>>> 2+3
>>> 2*3
>>> 2/3
>>> 2-3
>>> 2**3
>>> r=5
>>> r*2
What do these commands return?

Now try
>>> sin(pi/2)
Not working? That is because python only contains a very small number of simple syntax functions
and we need to call ‘modules’ containing additional functions to run those. To start with, numpy,
matplotlib, sympy are modules that you will quickly need - for numerical work, plotting, and symbolic
maths manipulation respectively.

[
If installed by method 1, you will need to update your module list at the command prompt (out of the
python interpreter)
$ pip install numpy
You will need to install any new modules you want to use in this way. ]

Now you need to call the module within the python interpreter before you can use the functions within
it e.g.
>>> import numpy as np
so that now you can call the function you wish to use within numpy by preceding its name with np. .

4
You will need to import the modules you want to use each time you start a piece of code.

Try
>>> import numpy as np
>>> np.sin(np.pi/2)
which should return sin(π/2)=1.

If you are interested in using the jupyter notebook interface, exit the interpreter (at the interpreter
prompt type >>> exit()), if you are not there already navigate to your python directory in the
command prompt (so that anything you now do in jupyter is within your python folder) and type
& jupyter notebook &

A jupyter home space opens in your internet browser. To open an empty notebook, select the ‘new’
dropdown menu and choose python 2. This opens a new page with an input cell and a toolbar. To give
your session a name, choose ‘rename’ from the ‘file’ menu and give the workbook a name. If you go
back to your jupyter ‘home’ tab, you will see your new workbook there listed as an ‘.ipynb’ file, running.

Now try executing the commands above in the jupyter notebook to check it produces the same results.
In the jupyter notebook, the In box is like the interpreter prompt, and to run the contents of the selected
box (cell), you need to click the run cell symbol ( >|) in the toolbar (shortcut Ctrl-enter). You can run
multiple cells from the ‘cell’ menu above the tool bar.

The print command

In python, print will display a string (a variable consisting of text characters). This is useful if you
want to display data, possibly to track the progress of a solution. Print displays to the computer screen
- there is no actual inkjet involved!

EXERCISE B
At the interpreter prompt type
>>> print ’Hello, World!’
What is returned?

Aside: In python 3, the print command has a slightly different syntax: print(’Hello, World!’) .

5
The most useful command?
>>> help()
or
>>> help(’print’)

Scripts

Typing at the command prompt is fine for very short routines, but typically you will want to combine a
longer sequence of commands. You can write a script within a text editor that you can read and execute
from the command line, or from within a workbook cell in jupyter. To work out how to write/edit a
script and execute at the command line, try writing your Hello, World! string in a script.

[For command line/text editor people. Open a new file in your chosen text editor. Using the syntax
you previously used at the interpreter prompt, type the command to display the string Hello, World!
Save the file in a sensible directory (I would suggest you give yourself a new folder in your home directory
called ‘python’ and save all the scripts you generate in this workshop to that folder) as test.py.

EXERCISE C (command line approach)


Open a new terminal/dos window and navigate to your new python directory with your script saved in
it. At the command prompt type
$ python test.py
What is returned?

From now on, you will write all your python in scripts and execute those scripts from the command
prompt in this way. If you want to test the odd line of code before putting in the script then you can
enter the python interpreter, as before. ]

Within the jupyter notebook go to your home tab and select ‘new’ → ‘text file’. Select ‘file’ → ‘save’
to give your script a name and the correct ‘.py’ ending to be recognised as a python script e.g. test.py
Using the syntax you previously used at the interpreter prompt, type into your script the commands to
display the string Hello, World! and save the file.

EXERCISE C (jupyter approach)


Now in the jupyter notepad, in the first cell type

6
>>> run test.py
and run that cell.
What is returned?

If you still have a python interpreter open in your command line, at the prompt type
>>> exit()
You have finished your first python session!

Further work

You now have python working on your laptop and can execute basic commands. For additional practice
go to the exercises in Think Python, chapter 1.
http://greenteapress.com/thinkpython/thinkpython.pdf

Acknowledgements

Thanks to Jack Pierce-Brown for advising on installation to Windows machines and supporting this
workshop.

7
Appendix

In the above, where is have started a line


>>>
this indicates a command you should enter at the python interpreter/jupyter cell.

Where a line starts


$
this indicates a command prompt or dos entry.

Python

Simple operators
+ addition
* multiplication
/ division
- subtraction
** to the power
import numpy as np within your script or session, use functions within the numpy module

Within numpy (as np.)


np.sin(θ) sin(θ)
np.cos(θ) cos(θ)
np.tan(θ) tan(θ)

Other operations
python open the python interpreter from the command prompt
python test.py run the python script test.py from the command prompt
run test.py run the python script test.py from a jupyter notebook cell
exit() close the python interpreter
print ’x’ display the string x
help() open the online help
help(’print’) open the online help on the page regarding the print function

8
UNIX

To navigate around your terminal/dos window, you’ll need to use some standard unix commands:
pwd tells you which directory you are currently in
ls lists the contents of that directory (terminal)
dir lists the contents of that directory (dos)
cd fld takes you into the folder fld, within the current directory
cd .. go back one folder
mkdir fld make a new folder in the current directory named fld
& forces the command prompt onto the next line while opening a subsidiary
window
→| complete the file path entry

You might also like