Introduction to Programming in Python¶
The goal of these notes is to help you to learn how to program. We will
be using the programming language Python, but you will be able to use
the skills you learn here with other programming systems such as Matlab, R or C.
Coding will also develop your creative problem solving skills.
Programming is a very important and useful skill for an engineer. Almost any job these days requires interaction with computer systems and many will require some level of programming. Engineering companies increasingly want to employ people with programming abilities and the ability to automate tasks with program scripts.
The skills you learn here can be used in automation of processes, computation of complex problems, control of equipment, instrumentation for making measurements, data analysis and producing figures of results. Additionally it can vastly speed up processing batches of text documents, accessing online data sources and any other task that would take unreasonably long times by hand.
What is Python?¶
Python is a programming language. It is free and open source and as such has many implemetations.
You typically type commands into a command window, code-block or script file, then run them. The Python interpreter reads the programme commands you give it and runs them to produce an output.
Why Use Python?¶
Python is good to learn how to program because it has a clear structure
and syntax compared to many programming languages.
It is easy to
use it to get started with basic programming and from there it is possible to
gradually teach yourself how to do much more advanced programming.
How To Use These Notes¶
To make the most of these notes it is important that you read through
each section,
enter and actually do all the examples and attempt the
problems in the course Notebooks.
You will have to return to earlier section as you work your way through.
Make your own notes, especially when you get stuck or something is not clear.
This will be helpful when you return to a problem later and also when
you have questions.
Some tips:
Try to predict what the output will be before running the examples. You should try to think through the steps of how the computer works through your programs.
It is often useful to work out some ideas with pen and paper before you start entering code.
Test your code. Always try a simple version of your program on examples where you know what the coutcome should be.
Ask questions to yourself such as:
“What would happen if I tried this?”
“Are there any input values for which the program does not work or gives the wrong answer?”
“Will someone else be able to understand the code I have just written?”
“Will I be able to understand this code in a few weeks time?”
Finally experiment! Instead of asking “what will happen if…?” or “will this work?” , just try it and see what happens. You are unlikely to break the computer by trying something out!
Python Versions¶
In these notes we use Python 3.8.
Python 3 was developed to clean up the design of the language.
Python 2 and Python 3 are mostly the same, but there are some
important incompatibilities, which means some code downloaded from the internet may need editing.
First Exercise¶
In Jupyter notebooks enter the following text into a new code cell then run it. If using Spyder, click on the bottom right hand console and type the following in front of the command prompt and press return:
print("Hello World!")
Hello World!
The output should appear as above.
next type the following and look at the output after hitting return:
7*6
42
Typing commands this way is a quick way of doing calculations and running commands, but if you want to do many in a row or repeat a task then it’s better to save them in a file and run then from there. This is called a script or program.
Writing a Script¶
A script file is a text file containing lines of code to be executed. The Python “interpreter” reads through the script line by line and executes the instructions in order, unless an error is encountered. An example is given below. The result of executing the script is shown underneath the code. In this case, the sentence “Hello World!” will be displayed. We will use the terms script file and program interchangeably.
#hello_world.py
print(42)
print("Hello World!")
42
Hello World!
The first line, starting with #
, is a comment. All comments are
ignored by the Python system, but they are nevertheless a very important
part of a program. They can help you and others understand the program.
The comment in the example gives the name of the file containing the
script, but this is not neccessary, just helpful information.
Exercise:¶
Create a new python script file in Spyder (or use a new Jupyter notebook) and type in all the three lines of the above
code.
Save the file as a Python script using the name hello_world.py
(go to File -> Download as
in Jupyter notebook).
Note the underscore _ is used not a space,
Never use spaces in program filenames!!!
Run this example in Spyder by pressing F5or the green run button or in a Jupyter notebook by pressing Ctrl+Return
.
As you may have already noticed, it is important to type in exactly the right commands. This is a good point to investigate what happens when something goes wrong when entering a program. Make a note of your observations.
Exercise:¶
Remove the hash symbol (
#
) in the first line of the program and run the program again.Remove one or both of the double quotes (“).
Replace the
print
function bypint
.
You will see that the Python system tries to provide helpful error messages to help you figure out what went wrong. Interpreting error messages and finding and fixing errors in programs is a crucial part of programming.
Types of Errors¶
There are three main types of errors:
Syntax errors: these will be detected when a program is read in by the Python system. An example of a syntax error is the use of
pint
instead of theprint
command in the example program. Syntax errors are reported by error messages.Runtime errors: these will be detected when the program is run. An example of a runtime error would be attempting to divide by zero or attempting to read from a file that does not exist. Add a line
print(1/0)
add the end of the example program and run it again. Note that the symbol/
denotes division. Runtime errors are reported by error messages.Logical errors: these are errors that cause the program to run but give the wrong result. Logical errors will not necessarily cause the program to stop with an error message. A very basic logical error in the example program would be any typo in the string
Hello World!
The program would still run, but it would give the wrong result. Try replacing the lineprint "Hello World!"
withprint "Hello Word!"
. Many logical errors can be detected by careful testing of a program.
An error message will usually contain an indication of where in the program the error occurred. Sometimes the real error may be on a earlier line than the one indicated in the error message.
To tackle errors when they happen try to look at the error message and identify the line where the first error occurs. Read the message carefully and compare it to your code to try to identify the problem. If you cannot figure out what it means then try typing the error message into google and looking at the suggested answers on web forums such as stackexchange.
Another way to debug code is to comment out lines using # a the beginning of a line, so that the interpreter ignores them. Then you can identify which line is giving the problem.
If there is no error message but your code does not work properly it can
be a good idea to insert print()
functions in different places to see
if the code is performing calculation steps as expected.