Python For Software Development Hans Petter Halvorsen
Python For Software Development Hans Petter Halvorsen
Python For Software Development Hans Petter Halvorsen
Development
Hans-Petter Halvorsen
OK Cancel
https://www.halvorsen.blog
Python for Software Development
Python for Software Development
Hans-Petter Halvorsen
2020
Python for Science and Engineering
Hans-Petter
c Halvorsen
September 9, 2020
1
Preface
Python is a popular programming language, and it is one of the most used pro-
gramming languages today.
Python works on all the main platforms and operating systems used today, such
Windows, macOS, and Linux.
Here you find lots of technical resources about Technology, Programming, Soft-
ware Engineering, Automation and Control, Industrial IT, etc.
https://www.halvorsen.blog/documents/programming/python/
These resources are a supplement to this textbook. Here you can download the
software, download code examples, etc.
LATEXis a document preparation system used for the communication and publi-
cation of scientific documents.
2
For more information about LATEX:
https://www.latex-project.org
Python Books
You find other Python textbooks within different domains on my Python Web
page:
https://www.halvorsen.blog/documents/programming/python/
Python Books:
3
Programming
The way we create software today has changed dramatically the last 30 years,
from the childhood of personal computers in the early 80s to today’s powerful
devices such as Smartphones, Tablets and PCs.
The Internet has also changed the way we use devices and software. We still
have traditional desktop applications, but Web Sites, Web Applications and so-
called Apps for Smartphones, etc. are dominating the software market today.
We need to find and learn Programming Languages that are suitable for the
New Age of Programming.
Software Engineering
Software Engineering is the discipline for creating software applications. A
systematic approach to the design, development, testing, and maintenance of
software.
• Planning
• Requirements Analysis
• Design
• Implementation
• Testing
4
5
Contents
2 What is Python? 19
2.1 Introduction to Python . . . . . . . . . . . . . . . . . . . . . . . 19
2.1.1 Interpreted vs. Compiled . . . . . . . . . . . . . . . . . . 20
2.2 Python Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
2.2.1 Python Packages for Science and Numerical Computations 22
2.3 Anaconda . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
2.4 Python Editors . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
2.4.1 Python IDLE . . . . . . . . . . . . . . . . . . . . . . . . . 23
2.4.2 Visual Studio Code . . . . . . . . . . . . . . . . . . . . . . 24
2.4.3 Spyder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
2.4.4 Visual Studio . . . . . . . . . . . . . . . . . . . . . . . . . 24
2.4.5 PyCharm . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
2.4.6 Wing Python IDE . . . . . . . . . . . . . . . . . . . . . . 25
2.4.7 Jupyter Notebook . . . . . . . . . . . . . . . . . . . . . . 25
2.5 Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
2.6 Installing Python . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
2.6.1 Python Windows 10 Store App . . . . . . . . . . . . . . . 26
2.6.2 Installing Anaconda . . . . . . . . . . . . . . . . . . . . . 26
2.6.3 Installing Visual Studio Code . . . . . . . . . . . . . . . . 26
6
3.5.4 Run Python Scripts from Spyder . . . . . . . . . . . . . . 35
II Python Programming 52
5 Python Programming 53
5.1 If ... Else . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
5.2 Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
5.3 For Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
5.3.1 Nested For Loops . . . . . . . . . . . . . . . . . . . . . . . 59
5.4 While Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
5.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
7
10 Error Handling in Python 81
10.1 Introduction to Error Handling . . . . . . . . . . . . . . . . . . . 81
10.1.1 Syntax Errors . . . . . . . . . . . . . . . . . . . . . . . . . 81
10.1.2 Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . 81
10.2 Exceptions Handling . . . . . . . . . . . . . . . . . . . . . . . . . 82
11 Debugging in Python 84
14 Anaconda 90
14.1 Anaconda Navigator . . . . . . . . . . . . . . . . . . . . . . . . . 90
14.2 Anaconda Prompt . . . . . . . . . . . . . . . . . . . . . . . . . . 90
15 Enthought Canopy 93
IV Python Editors 94
16 Python Editors 95
17 Spyder 97
17.1 Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
20 PyCharm 110
8
V Data Acquisition (DAQ) with Python 117
23 Plotting Sensor Data 118
23.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
23.2 Introduction to Real-Time Plotting . . . . . . . . . . . . . . . . . 118
23.3 Real-Time Plotting with Animation . . . . . . . . . . . . . . . . 120
23.3.1 Speeding Up the Plot Animation . . . . . . . . . . . . . . 122
9
29 MongoDB with Python 152
29.1 Introduction to MongoDB . . . . . . . . . . . . . . . . . . . . . . 152
29.2 MongoDB with Python . . . . . . . . . . . . . . . . . . . . . . . 152
29.2.1 PyMongo . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
29.3 Additional Resources . . . . . . . . . . . . . . . . . . . . . . . . . 153
10
VIII Python PyQt GUI Development 172
37 Getting Started with PyQt 173
37.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
37.2 Introduction to Qt . . . . . . . . . . . . . . . . . . . . . . . . . . 173
37.3 Introduction to PyQt . . . . . . . . . . . . . . . . . . . . . . . . . 174
37.3.1 PyQtChart . . . . . . . . . . . . . . . . . . . . . . . . . . 174
37.4 Installing PyQt . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
37.4.1 Installation of PyQt . . . . . . . . . . . . . . . . . . . . . 175
37.4.2 Installation of Qt Designer . . . . . . . . . . . . . . . . . 175
37.4.3 Installation of PyQtChart . . . . . . . . . . . . . . . . . . 175
37.5 PyQt Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176
37.6 PyQt Widgets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178
37.7 Event Handling in PyQt . . . . . . . . . . . . . . . . . . . . . . . 181
37.8 PyQt Designer . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
37.9 PyQt Applications Examples . . . . . . . . . . . . . . . . . . . . 184
IX Resources 186
38 Python Resources 187
38.1 Python Distributions . . . . . . . . . . . . . . . . . . . . . . . . . 187
38.2 Python Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
38.3 Python Editors . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
38.4 Python Tutorials . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
38.5 Python in Visual Studio . . . . . . . . . . . . . . . . . . . . . . . 188
11
Part I
12
Chapter 1
Introduction
With this textbook you will learn basic Python programming. The textbook
contains lots of examples and self-paced tasks that the users should go through
and solve in their own pace.
The Internet has also changed the way we use devices and software. We still
have traditional desktop applications, but Web Sites, Web Applications and so-
called Apps for Smartphones, etc. are dominating the software market today.
We need to find and learn Programming Languages that are suitable for the
New Age of Programming.
13
Figure 1.1: Web Site - Python
Python has during the last 10 years become more and more popular. Today,
Python has become one of the most popular Programming Languages.
There are many different rankings regarding which programming language which
is most popular. In most of these ranking, Python is in top 10.
One of these rankings is the IEEE Spectrum’s ranking of the top programming
languages [3].
From this ranking we see that Python is the most popular Programming Lan-
guage in 2018. See Figure 1.2
As we see in Figure 1.2 they categorize the different Programming Languages
into the following categories:
• Web
14
Figure 1.2: The Most Popular Programming Languages
• Mobile
• Enterprise
• Embedded
According to Figure 1.2 we see that Python can be used to program Web Ap-
plications, Enterprise Applications and Embedded Applications.
So far Python is not used or not optimized for creating Mobile Applications. We
have today 2 major Mobile platforms; iOS Applications are mainly programmed
with the Swift Programming language, while Android Applications are mainly
programmed with either Java or Kotlin.
Another survey is the ”Stack Overflow Developer Survey 2018” [4]. See Figure
1.3.
As we can see from [5] and Figure 1.4, Python becomes more and more popular
year by year.
Based on Figure 1.4, the source [5] try to predict the future of Python, see
Figure 1.5.
Based on the surveys and statistics mention above, obviously Python is a pro-
gramming language that you should learn.
Lets summarize:
• Python is fun to learn and use and it is also named after the British
comedy group called Monty Python.
• Python has a simple and flexible code structure and the code is easy to
read.
15
Figure 1.3: The Top Programming Languages - Stack Overflow Survey
16
Figure 1.4: The Incredible Growth of Python
• Databases (such as SQL Server and MySQL) and using the Structured
Query Language (SQL) or the upcoming NoSQL databases
• App Development for the 2 main platforms iOS (XCode using the Swift
Programming Language) and Android (Android Studio using the Java
Programming Language or Kotlin Programming language)
If you have skills in most of the tools, programming languages and frameworks
mention above, you are well suited for working as a full-time programmer or
software engineer.
1.2 MATLAB
If you are looking for MATLAB, please see the following:
https://www.halvorsen.blog/documents/programming/matlab/
17
Figure 1.5: The Future of Python
18
Chapter 2
What is Python?
But this is just the Python core, i.e. the interpreter a very basic editor, and the
minimum needed to create basic Python programs.
Typically you will need more features for solving your tasks. Then you can in-
stall and use separate Python packages created by third parties. These packages
need to be downloaded and installed separately (typically you use something
called PIP), or you choose to use, e.g., a distribution package like Anaconda.
19
Figure 2.1: IDLE - Basic Python Editor
you write Python (.py) files in a text editor and then put those files into the
python interpreter to be executed. Depending on the Editor you are using, this
is either done automatically, or you need to do it manually.
20
With interpreted languages, the code is saved in the same format that you en-
tered. Compiled programs generally run faster than interpreted ones because
interpreted programs must be reduced to machine instructions at run-time. It
is usually easier to develop applications in an interpreted environment because
you don’t have to recompile your application each time you want to test a small
section.
Compiled languages are all translated by running the source code through a
compiler. This results in very efficient code that can be executed any number of
times. The overhead for the translation is incurred just once, when the source
is compiled; thereafter, it need only be loaded and executed.
During the design of an application, you might need to decide whether to use a
compiled language or an interpreted language for the application source code.
Thus, an interpreted language is generally more suited for doing ”ad hoc” cal-
culations or simulations, while compiled languages are better for permanent
applications where speed is in focus.
This is also typical approach for open source software, because everybody can
create their own Python packages and distribute them. In that way you also
find Python packages for almost everything, from Scientific Computing to Web
Development.
21
These packages need to be downloaded and installed separately, or you choose
to use, e.g., a distribution package like Anaconda, where you typically get the
packages you need for scientific computing. With Anaconda you typically get
the same features as with MATLAB.
Lots of Python packages exists, depending on what you are going to solve.
We have Python packages for Desktop GUI Development, Database Develop-
ment, Web Development, Software Development, etc.
Here you can search for, download and install many hundreds Python Packages
within different topics and applications. You can also make your own Python
Packages and distribute them here.
2.3 Anaconda
Anaconda is a distribution package, where you get Python compiler, Python
packages and the Spyder editor, all in one package.
Anaconda includes Python, the Jupyter Notebook, and other commonly used
packages for scientific computing and data science.
22
They offer a free version (Anaconda Distribution) and a paid version (Enter-
prise) Anaconda is available for Windows, macOS, and Linux
Web:
https://www.anaconda.com
Wikipedia:
https://en.wikipedia.org/wiki/Anaconda( P ythond istribution)
Spyder and the Python packages (NumPy, SciPy, Matplotlib, ...) mention above
+++ are included in the Anaconda Distribution.
Which editor you should use depends on your background, what kind of code
editors you have used previously, your programming skills, what your are going
to develop in Python, etc.
Web:
https://www.python.org
23
2.4.2 Visual Studio Code
Visual Studio Code is a source code editor developed by Microsoft for Windows,
Linux and macOS.
Web:
https://code.visualstudio.com
2.4.3 Spyder
Spyder is an open source cross-platform integrated development environment
(IDE) for scientific programming in the Python language.
Web:
https://www.spyder-ide.org
Wikipedia:
https://en.wikipedia.org/wiki/Spyder( sof tware)
Visual Studio (from 2017), has integrated support for Python, it is called
”Python Support in Visual Studio”.
Web:
https://visualstudio.microsoft.com
Wikipedia:
https://en.wikipedia.org/wiki/MicrosoftV isualS tudio
2.4.5 PyCharm
PyCharm is cross-platform, with Windows, macOS and Linux versions. The
Community Edition is free to use, while the Professional Edition (paid version)
has some extra features.
24
Web:
https://www.jetbrains.com/pycharm/
• Wing 101 – a very simplified free version, for teaching beginning pro-
grammers
• Wing Personal – free version that omits some features, for students and
hobbyists
• Wing Pro – a full-featured commercial (paid) version, for professional
programmers
Web:
http://jupyter.org
Wikipedia:
https://en.wikipedia.org/wiki/ProjectJ upyter
2.5 Resources
Here are some useful Python resources:
• The official Python Tutorial
- https://docs.python.org/3.7/tutorial/index.html
• The official Python Documentation
- https://docs.python.org/3.7/index.html
• Python Tutorial (w3schools.com) [13]
- https://www.w3schools.com/python/
25
https://www.python.org
Here you can download the basic Python features in one package, which includes
the Python programming language interpreter, and a basic code editor, or an
integrated development environment, called IDLE. See Figure 2.1
For more advanced Python Programming you typically need a better Code Ed-
itor and additional Packages.
For the basic Python examples in the beginning, the basic Python software
from:
https://www.python.org is good enough.
I suggest you start with the basic Python software in order to learn the basics,
then you can upgrade to a better Editor, install addition Python packages (either
manually or or install Anaconda where ”everything” is included).
The Microsoft Store version of Python 3.7 is a simplified installer for running
scripts and packages.
Microsoft Store version of Python 3.7 is very basic but it’s good enough to run
the simple scripts.
Python 3.7 Microsoft Store edition will receive all updates automatically when
they are released and no manual action is required from your end.
In order to install the Microsoft Store version of Python just open Microsoft
Store in Windows 10 and search for Python.
26
Download and install from:
https://code.visualstudio.com
27
Chapter 3
Other Python Editors will be discussed more in detail later. For now you can
use the basic Python IDE (IDLE) or Spyder if you have installed the Anaconda
distribution package.
28
Example 3.2.1. Plotting in Python
Lets open your Python Editor and type the following:
1 p r i n t ( ” H e l l o World ! ” )
Listing 3.1: Hello World Python Example
[End of Example]
You can use Python in different ways, either in ”interactive” mode or in ”Script-
ing” mode.
The python program that you have installed will by default act as something
called an interpreter. An interpreter takes text commands and runs them as
you enter them - very handy for trying things out.
Yo can run Python interactively in different ways either using the Console which
is part of the operating system or the Python IDLE and the Python Shell which
is part of the basic Python installation from https://www.python.org.
Here you type one and one command at a time after the ”>>>” sign in the
Python Shell.
1 >>> p r i n t ( ” H e l l o World ! ” )
The python program that you have installed will by default act as something
called an interpreter. An interpreter takes text commands and runs them as
you enter them - very handy for trying things out.
Below we see how we can run Python from the Console which is part of the OS.
29
3.4.1 Opening the Console on macOS
The standard console on macOS is a program called Terminal. Open Terminal
by navigating to Applications, then Utilities, then double-click the Terminal pro-
gram. You can also easily search for it in the system search tool in the top right.
The command line Terminal is a tool for interacting with your computer. A
window will open with a command line prompt message, something like this:
L a s t l o g i n : Tue Dec 11 0 8 : 3 3 : 5 1 on c o n s o l e
computername : ˜ username
Just type python at your console, hit Enter, and you should enter Python’s
Interpreter.
1 L a s t l o g i n : Tue Dec 11 1 2 : 3 4 : 1 6 on t t y s 0 0 0
2 Hans−P e t t e r −Work−MacBook−A i r : ˜ hansha$ python
3 Python 3 . 6 . 5 | Anaconda , I n c . | ( d e f a u l t , Apr 26 2 0 1 8 , 0 8 : 4 2 : 3 7 )
4 [GCC 4 . 2 . 1 Compatible Clang 4 . 0 . 1 ( t a g s /RELEASE 401/ f i n a l ) ] on
darwin
5 Type ” h e l p ” , ” c o p y r i g h t ” , ” c r e d i t s ” o r ” l i c e n s e ” f o r more
information .
6 >>>
The prompt >>> on the last line indicates that you are now in an interactive
Python interpeter session, also called the “Python shell”. This is different from
the normal terminal command prompt!
You can now enter some code for python to run. Try:
>>> p r i n t ( ” H e l l o World ” )
30
3.4.2 Opening the Console on Windows
Window’s console is called the Command Prompt, named cmd. An easy way to
get to it is by using the key combination Windows+R (Windows meaning the
windows logo button), which should open a Run dialog. Then type cmd and
hit Enter or click Ok.
Just type python in the Command Prompt, hit Enter, and you should enter
Python’s Interpreter. See Figure 3.3.
Note! This is also an option during the setup. While installing you can se-
lect ”Add Python.exe to path”. This option is by default set to ”Off”. To get
that option you need to select ”Customize”, not using the ”Default” installation.
In the window that appears, click Environment Variables. . . near the bottom
right. See Figure 3.4.
31
Figure 3.4: Windows System Properties
In the next window, find and select the user variable named Path and click
Edit. . . to change its value. See Figure 3.5.
Select ”New” and add the path where ”python.exe” is located. See Figure 3.6.
Click Save and open the Command Prompt once more and enter ”python” to
verify it works. See Figure 3.3.
32
Figure 3.5: Windows System Properties
In Figure 3.7 we see how this is done. As you see we can enter many Python
commands that together makes a Python program or Python script.
From the Python Shell you select Run → Run Module or hit F5 in order to run
or execute the Python Script. See Figure 3.8.
33
Figure 3.6: Windows System Properties
The IDLE editor is very basic, for more complicated tasks you typically may
prefer to use another editor like Spyder, Visual Studio Code, etc.
1 $ cd / U s e r s / username / Downloads
2 $ python h e l l o w o r l d . py
Note! Make sure you are at your system command prompt, which will have $
or > at the end, not in Python mode (which has >>> instead)!
1 Hello
2 World
3 How a r e you ?
34
Figure 3.7: Python Script
1 > cd /
2 > cd Temp
3 > python h e l l o w o r l d . py
Note! Make sure you are at your system command prompt, which will have >
at the end, not in Python mode (which has >>> instead)!
1 Hello
2 World
3 How a r e you ?
In the Spyder editor we have the Script Editor to the left and the interactive
Python Shell or the Console window to the right. See See 3.11.
35
Figure 3.8: Running a Python Script
36
Figure 3.11: Running a Python Script in Spyder
37
Chapter 4
1 p r i n t ( ” H e l l o World ! ” )
Listing 4.1: Hello World Python Example
[End of Example]
Press q to close the help window and return to the Python prompt.
4.2 Variables
Variables are defined with the assignment operator, “=”. Python is dynamically
typed, meaning that variables can be assigned without declaring their type, and
that their type can change. Values can come from constants, from computation
involving values of other variables, or from the output of a function.
38
Example 4.2.1. Creating and using Variables in Python
We use the basic IDLE (or another Python Editor) and type the following:
1 >>> x = 3
2 >>> x
3 3
Listing 4.2: Using Variables in Python
Here we define a variable and sets the value equal to 3 and then print the result
to the screen.
[End of Example]
You can write one command by time in the IDLE. If you quit IDLE the variables
and data are lost. Therefore, if you want to write a somewhat longer program,
you are better off using a text editor to prepare the input for the interpreter
and running it with that file as input instead. This is known as creating a script.
Python scripts or programs are save as a text file with the extension .py
As seen in the examples, you can use the print() command in order to show the
values on the screen.
[End of Example]
39
A variable can have a short name (like x and y) or a more descriptive name
(sum, amount, etc).
You don need to define the variables before you use them (like you need to to
in, e.g., C/C++/C).
Figure 4.1 show these examples using the basic IDLE editor.
4.2.1 Numbers
There are three numeric types in Python:
• int
• float
• complex
40
Variables of numeric types are created when you assign a value to them, so in
normal coding you don’t need to bother.
1 x = 1 # int
2 y = 2.8 # float
3 z = 3 + 2j # complex
Listing 4.5: Numeric Types in Python
This means you just assign values to a variable without worrying about what
kind of data type it is.
1 p r i n t ( type ( x ) )
2 p r i n t ( type ( y ) )
3 p r i n t ( type ( z ) )
Listing 4.6: Check Data Types in Python
If you use the Spyder Editor, you can see the data types that a variable has
using the Variable Explorer (Figure 4.2):
[End of Example]
4.2.2 Strings
Strings in Python are surrounded by either single quotation marks, or double
quotation marks. ’Hello’ is the same as ”Hello”.
Strings can be output to screen using the print function. For example: print(”Hello”).
1 a = ” H e l l o World ! ”
2
3 print (a)
4
5 print (a [ 1 ] )
6 print (a [ 2 : 5 ] )
7 print ( len (a) )
8 print ( a . lower () )
41
9 p r i n t ( a . upper ( ) )
10 p r i n t ( a . r e p l a c e ( ”H” , ”J” ) )
11 print (a . s p l i t (” ”) )
Listing 4.7: Strings in Python
As you see in the example, there are many built-in functions form manipulating
strings in Python. The Example shows only a few of them.
Strings in Python are arrays of bytes, and we can use index to get a specific
character within the string as shown in the example code.
[End of Example]
[End of Example]
In another chapter we will learn to create our own functions from scratch.
42
4.4 Python Standard Library
Python allows you to split your program into modules that can be reused in
other Python programs. It comes with a large collection of standard modules
that you can use as the basis of your programs.
The Python Standard Library consists of different modules for handling file
I/O, basic mathematics, etc. You don’t need to install these separately, but you
need to important them when you want to use some of these modules or some
of the functions within these modules.
The math module has all the basic math functions you need, such as: Trigono-
metric functions: sin(x), cos(x), etc. Logarithmic functions: log(), log10(), etc.
Constants like pi, e, inf, nan, etc.
43
We can also write it like this:
1 im po rt math a s mt
2
3 x = 3.14
4 y = mt . s i n ( x )
5
6 print (y)
[End of Example]
There are advantages and disadvantages with the different approaches. In your
program you may need to use functions from many different modules or pack-
ages. If you import the whole module instead of just the function(s) you need
you use more of the computer memory.
Very often we also need to import and use multiple libraries where the different
libraries have some functions with the same name but different use.
Other useful modules in the Python Standard Library are statistics (where
you have functions like mean(), stdev(), etc.)
For more information about the functions in the Python Standard Library,
see:
https://docs.python.org/3/library/index.html
44
Lots of other packages exists, depending on what you are going to solve.
You will learn the basics features in all these libraries. We will use all of the in
different examples and exercises throughout this textbook.
Example 4.5.1. Using libraries
In this example we use the NumPy library:
1 im po rt numpy a s np
2
3 x = 3
4
5 y = np . s i n ( x )
6
7 print (y)
In this example we use both the math module in the Python Standard Library
and the NumPy library:
1 im po rt math a s mt
2 im po rt numpy a s np
3
4 x = 3
5
6 y = mt . s i n ( x )
7
8 print (y)
9
10
11 y = np . s i n ( x )
12
13 print (y)
Note! As seen in this example we use a function called sin() which exists both
in the math module in the Python Standard Library and the NumPy library.
In this case they give the same results. In this case the following code is not
recommended:
1 from math im por t ∗
2 from numpy imp ort ∗
3
4 x = 3
5
45
6 y = sin (x)
7
8 print (y)
9
10
11 y = sin (x)
12
13 print (y)
In this case it works, but assume you have 2 different functions with the same
name that have different meaning in 2 different libraries.
[End of Example]
Anaconda:
https://www.anaconda.com/distribution/
If you are familiar with MATLAB and basic plotting in MATLAB, using the
Matplotlib is very similar.
The main difference from MATLAB is that you need to import the library,
either the whole library or one or more functions.
For simplicity we import the whole library like this:
1 im po rt m a t p l o t l i b . p y p l o t a s p l t
46
Plotting functions that you will use a lot:
• plot()
• title()
• xlabel()
• ylabel()
• axis()
• grid()
• subplot()
• legend()
• show()
Lets create some basic plotting examples using the Matplotlib library:
This makes the code simpler to read. one problem with this approach appears
assuming we import and use multiple libraries and the different libraries have
some functions with the same name but different use.
47
Figure 4.3: Plotting in Python
[End of Example]
• plot()
• xlabel()
• ylabel()
• show()
1 im po rt numpy a s np
2 im po rt m a t p l o t l i b . p y p l o t a s p l t
3
4 x = [0 , 1 , 2 , 3 , 4 , 5 , 6 , 7]
5
6 y = np . s i n ( x )
7
8 plt . plot (x , y)
9 plt . xlabel ( ’x ’ )
10 plt . ylabel ( ’y ’ )
11 plt . show ( )
48
Figure 4.4: Plotting a Sine function in Python
1 im po rt m a t p l o t l i b . p y p l o t a s p l t
2 im po rt numpy a s np
3
4 xstart = 0
5 x s t o p = 2∗ np . p i
6 increment = 0.1
7
8 x = np . a r a n g e ( x s t a r t , xstop , i n c r e m e n t )
9
10 y = np . s i n ( x )
11
12 plt . plot (x , y)
13 plt . xlabel ( ’x ’ )
14 plt . ylabel ( ’y ’ )
15 plt . show ( )
[End of Example]
4.6.1 Subplots
The subplot command enables you to display multiple plots in the same window.
Typing ”subplot(m,n,p)” partitions the figure window into an m-by-n matrix
of small subplots and selects the subplot for the current plot. The plots are
numbered along the first row of the figure window, then the second row, and so
on. See Figure 4.6.
49
Figure 4.5: Plotting a Sine function in Python - Better Implementation
[End of Example]
50
Figure 4.6: Creating Subplots in Python
4.6.2 Exercises
Below you find different self-paced Exercises that you should go through and
solve on your own. The only way to learn Python is to do lots of Exercises!
You should use all the Plotting functions listed below in your code:
• plot()
• title()
• xlabel()
• ylabel()
• axis()
• grid()
• legend()
• show()
[End of Exercise]
51
Part II
Python Programming
52
Chapter 5
Python Programming
We have been through the basics in Python, such as variables, using some basic
built-in functions, basic plotting, etc.
You may come far only using these thins, but to create real applications, you
need to know about and use features like:
• If ... Else
• For Loops
• While Loops
• Arrays ...
If you are familiar with one or more other programming language, these fea-
tures should be familiar and known to you. All programming languages have
these features built-in, but the syntax is slightly different from one language to
another.
53
11 p r i n t ( ” a i s e q u a l t o b” )
Listing 5.1: If
Using If - Else:
1 a = 5
2 b = 8
3
4 if a > b:
5 p r i n t ( ” a i s g r e a t e r than b” )
6 else :
7 p r i n t ( ”b i s g r e a t e r than a o r a and b a r e e q u a l ” )
Listing 5.2: If - Else
Using Elif :
1 a = 5
2 b = 8
3
4 if a > b:
5 p r i n t ( ” a i s g r e a t e r than b” )
6 elif b > a:
7 p r i n t ( ”b i s g r e a t e r than a ” )
8 e l i f a == b :
9 p r i n t ( ” a i s e q u a l t o b” )
Listing 5.3: Elif
Note! Python uses ”elif” not ”elseif” like many other programming languages
do.
[End of Example]
5.2 Arrays
An array is a special variable, which can hold more than one value at a time.
Here are some Examples how you can create and use Arrays in Python:
Example 5.2.1. Arrays in Python
1 data = [ 1 . 6 , 3 . 4 , 5 . 5 , 9 . 4 ]
2
3 N = l e n ( data )
4
5 p r i n t (N)
6
7 p r i n t ( data [ 2 ] )
8
9 data [ 2 ] = 7 . 3
10
11 p r i n t ( data [ 2 ] )
54
12
13
14 f o r x i n data :
15 print (x)
16
17
18 data . append ( 1 1 . 4 )
19
20
21 N = l e n ( data )
22
23 p r i n t (N)
24
25
26 f o r x i n data :
27 print (x)
Listing 5.4: Using Arrays in Python
You can return the number of elements in the array like this:
1 N = l e n ( data )
You can get a specific value inside the array like this:
1 index = 2
2 x = cars [ index ]
[End of Example]
You have many built in methods you can use in combination with arrays, like
sort(), clear(), copy(), count(), insert(), remove(), etc.
55
5.3 For Loops
A For loop is used for iterating over a sequence. I guess all your programs will
use one or more For loops. So if you have not used For loops before, make sure
to learn it now.
Below you see a basic example how you can use a For loop in Python:
1 f o r i in range (1 , 10) :
2 print ( i )
The For loop is probably one of the most useful feature in Python (or in any
kind of programming language). Below you will see different examples how you
can use a For loop in Python.
1 data = [ 1 . 6 , 3 . 4 , 5 . 5 , 9 . 4 ]
2
3 f o r x i n data :
4 print (x)
5
6
7 c a r l i s t = [ ” Volvo ” , ” T e s l a ” , ” Ford ” ]
8
9 for car in c a r l i s t :
10 print ( car )
Listing 5.5: Using For Loops in Python
Finally, you can also use the range() function like this:
1 start = 4
2 s t o p = 12 #but not i n c l u d i n g
3 step = 2
4
5 f o r x i n r a n g e ( s t a r t , s top , s t e p ) :
6 print (x)
56
You should try all these examples in order to learn the basic structure of a For
loop.
[End of Example]
[End of Example]
By definition, the first two Fibonacci numbers are 0 and 1, and each subsequent
number is the sum of the previous two.
Some sources omit the initial 0, instead beginning the sequence with two 1s.
57
In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the
recurrence relation
f0 = 0, f1 = 1
We will write a Python script that calculates the N first Fibonacci numbers.
The Python Script becomes like this:
1 N = 10
2
3 fib1 = 0
4 fib2 = 1
5
6 print ( fib1 )
7 print ( fib2 )
8
9 f o r k i n r a n g e (N−2) :
10 f i b n e x t = f i b 2 +f i b 1
11 fib1 = fib2
12 fib2 = fib next
13 print ( fib next )
Listing 5.6: Fibonacci Numbers Using a For Loop in Python
Alternative solution:
1 N = 10
2
3 fib = [0 , 1]
4
5
6 f o r k i n r a n g e (N−2) :
7 f i b n e x t = f i b [ k +1] +f i b [ k ]
8 f i b . append ( f i b n e x t )
9
10 print ( fib )
Listing 5.7: Fibonacci Numbers Using a For Loop in Python - Alt2
58
11 f o r k i n r a n g e (N−2) :
12 f i b [ k +2] = f i b [ k +1] +f i b [ k ]
13
14
15 print ( fib )
Listing 5.8: Fibonacci Numbers Using a For Loop in Python - Alt3
[End of Example]
Simple example:
1 f o r i in range (1 , 10) :
2 f o r k in range (1 , 10) :
3 print ( i , k)
59
By definition a prime number has both 1 and itself as a divisor. If it has any
other divisor, it cannot be prime.
Create a Python Script where you find all prime numbers between 1 and 200.
Tip! I guess this can be done in many different ways, but one way is to use 2
nested For Loops.
[End of Exercise]
1 m = 8
2
3 while m > 2:
4 p r i n t (m)
5 m = m− 1
Listing 5.10: Using While Loops in Python
[End of Example]
5.5 Exercises
Below you find different self-paced Exercises that you should go through and
solve on your own. The only way to learn Python is to do lots of Exercises!
60
where T is the time constant.
Create a Script in Python (.py file) where you plot the solution x(t) in the time
interval:
0 ≤ t ≤ 25
Add Grid, and proper Title and Axis Labels to the plot.
[End of Exercise]
61
Chapter 6
Creating Functions in
Python
6.1 Introduction
A function is a block of code which only runs when it is called. You can pass
data, known as parameters, into a function. A function can return data as a
result.
If you are familiar with one or more other programming language, creating and
using functions should be familiar and known to you. All programming lan-
guages has the possibility to create functions, but the syntax is slightly different
from one language to another.
Scripts:
• A collection of commands that you would execute in the Editor
• Used for automating repetitive tasks
Functions:
• Operate on information (inputs) fed into them and return outputs
• Have a separate workspace and internal variables that is only valid inside
the function
62
• Your own user-defined functions work the same way as the built-in func-
tions you use all the time, such as plot(), rand(), mean(), std(), etc.
Python have lots of built-in functions, but very often we need to create our own
functions (we could refer to these functions as user-defined functions)
In Python a function is defined using the def keyword:
1 d e f FunctionName :
2 <s t a t e m e n t −1>
3 .
4 .
5 <s t a t e m e n t −N>
6 return . . .
The function adds 2 numbers. The name of the function is add, and it returns
the answer using the return statement.
Note that you need to use a colon ”:” at the end of line where you define the
function.
1 d e f add ( x , y ) :
63
[End of Example]
Next, we create a new Python File (e.g., testaverage.py) where we use the
function we created:
1 from m y f u n c t i o n s im po rt a v e r a g e
2
3 a = 2
4 b = 3
5
6 c = average (a , b)
7
8 print ( c )
Listing 6.4: Test of Average function
[End of Example]
64
21 data = [ 1 , 5 , 6 , 3 , 1 2 , 3 ]
22
23
24 t o t a l s u m , mean = s t a t ( data )
25
26 p r i n t ( t o t a l s u m , mean )
Listing 6.5: Function with multiple return values
[End of Example]
6.3 Exercises
Below you find different self-paced Exercises that you should go through and
solve on your own. The only way to learn Python is to do lots of Exercises!
[End of Exercise]
Exercise 6.3.2. Create Python functions for converting between radians and
degrees
Since most of the trigonometric functions require that the angle is expressed in
radians, we will create our own functions in order to convert between radians
and degrees.
We have that:
65
[End of Exercise]
By definition, the first two Fibonacci numbers are 0 and 1, and each subsequent
number is the sum of the previous two.
Some sources omit the initial 0, instead beginning the sequence with two 1s.
f0 = 0, f1 = 1
[End of Exercise]
By definition a prime number has both 1 and itself as a divisor. If it has any
other divisor, it cannot be prime.
Tip! I guess this can be implemented in many different ways, but one way is to
use 2 nested For Loops.
66
Create a Python function where you check if a given number is a prime number
or not.
You can check the function in the Command Window like this:
1 number = 4
2 c h e c k i f p r i m e ( number )
[End of Exercise]
67
Chapter 7
7.1 Introduction
Python is an object oriented programming (OOP) language. Almost everything
in Python is an object, with its properties and methods.
The foundation for all object oriented programming (OOP) languages are Classes.
1 c l a s s ClassName :
2 <s t a t e m e n t −1>
3 .
4 .
5 .
6 <s t a t e m e n t −N>
1 c l a s s Car :
2 model = ” Volvo ”
3 c o l o r = ” Blue ”
4
5
6 c a r = Car ( )
7
8
9 p r i n t ( c a r . model )
10 print ( car . color )
Listing 7.1: Simple Python Class
68
This example don’t illustrate the good things with classes so we will create some
more examples.
[End of Example]
[End of Example]
69
12 c a r 2 = Car ( ” Volvo ” , ” Blue ” )
13
14 p r i n t ( c a r 2 . model )
15 print ( car2 . c o l o r )
Listing 7.3: Python Class Constructor Example
As you see from the code we have now defined a Class ”Car” that has 2 Class
variables called ”model” and ”color”, and in addition we have defined a Func-
tion (or Method) called ”displayCar()”.
Its normal to use the term ”Method” for Functions that are defined within a
Class.
You declare class methods like normal functions with the exception that the
first argument to each method is self.
To create instances of a class, you call the class using class name and pass in
whatever arguments its init () method accepts.
For example:
70
1 c a r 1 = Car ( ” T e s l a ” , ”Red” )
[End of Example]
Then we create a Python Script (testCar.py) where we are using the Class:
1 # I m p o r t i n g t h e Car C l a s s
2 from Car im por t Car
3
4 # Lets s t a r t using the Class
5
6 c a r 1 = Car ( ” T e s l a ” , ”Red” )
7
8 car1 . displayCar ()
9
10
11 c a r 2 = Car ( ” Ford ” , ” Green ” )
12
13 p r i n t ( c a r 2 . model )
14 print ( car2 . c o l o r )
15
16
17 c a r 3 = Car ( ” Volvo ” , ” Blue ” )
18
19 p r i n t ( c a r 3 . model )
20 print ( car3 . c o l o r )
21
22 c a r 3 . c o l o r=” Black ”
23
24 car3 . displayCar ()
Listing 7.6: Script that is using the Class
[language=Python]
[End of Example]
71
7.3 Exercises
Below you find different self-paced Exercises that you should go through and
solve on your own. The only way to learn Python is to do lots of Exercises!
[End of Exercise]
72
Chapter 8
As your program gets longer, you may want to split it into several files for easier
maintenance. You may also want to use a handy function that you have written
in several programs without copying its definition into each program.
To support this, Python has a way to put definitions in a file and use them
in a script or in an interactive instance of the interpreter (the Python Console
window).
Python allows you to split your program into modules that can be reused in
other Python programs. It comes with a large collection of standard modules
that you can use as the basis of your programs as we have seen examples of in
previous chapters. Not it is time to make your own modules from scratch.
Previously you have been using different modules, libraries or packages created
by the Python organization or by others. Here you will create your own modules
from scratch.
73
The formula for converting from Fahrenheit to Celsius is:
8.2 Exercises
Below you find different self-paced Exercises that you should go through and
solve on your own. The only way to learn Python is to do lots of Exercises!
Exercise 8.2.1. Create Python Module for converting between radians and
degrees
Since most of the trigonometric functions require that the angle is expressed in
radians, we will create our own functions in order to convert between radians
74
and degrees.
Create two functions that convert from radians to degrees (r2d(x)) and from
degrees to radians (d2r(x)) respectively.
Test the functions to make sure that they work as expected. You can choose to
make a new .py file to test these functions or you can use the Console window.
[End of Exercise]
75
Chapter 9
9.1 Introduction
Python has several functions for creating, reading, updating, and deleting files.
The key function for working with files in Python is the open() function.
• ”x” - Create - Creates the specified file, returns an error if the file exists
• ”w” - Write - Opens a file for writing, creates the file if it does not exist
• ”r” - Read - Default value. Opens a file for reading, error if the file does
not exist
• ”a” - Append - Opens a file for appending, creates the file if it does not
exist
In addition you can specify if the file should be handled as binary or text mode
• ”x” - Create - Creates the specified file, returns an error if the file exists
• ”w” - Write - Opens a file for writing, creates the file if it does not exist
• ”a” - Append - Opens a file for appending, creates the file if it does not
exist
76
To write to an Existing file, you must add a parameter to the open() function:
• ”w” - Write - Opens a file for writing, creates the file if it does not exist
• ”a” - Append - Opens a file for appending, creates the file if it does not
exist
1 f = open ( ” m y f i l e . t x t ” , ”x” )
2
3 data = ” Helo World”
4
5 f . w r i t e ( data )
6
7 f . close ()
Listing 9.1: Write Data to a File
[End of Example]
• ”r” - Read - Default value. Opens a file for reading, error if the file does
not exist
1 f = open ( ” m y f i l e . t x t ” , ” r ” )
2
3 data = f . r e a d ( )
4
5 p r i n t ( data )
6
7 f . close ()
Listing 9.2: Read Data from a File
[End of Example]
77
1 data = [ 1 . 6 , 3 . 4 , 5 . 5 , 9 . 4 ]
2
3 f = open ( ” m y f i l e . t x t ” , ”x” )
4
5 f o r v a l u e i n data :
6 record = s t r ( value )
7 f . write ( record )
8 f . w r i t e ( ” \n” )
9
10 f . close ()
Listing 9.3: Logging Data to File
[End of Example]
1 f = open ( ” m y f i l e . t x t ” , ” r ” )
2
3 for record in f :
4 r e c o r d = r e c o r d . r e p l a c e ( ” \n” , ” ” )
5 print ( record )
6
7 f . close ()
Listing 9.4: Read Logged Data from File
[End of Example]
9.6 Exercises
Below you find different self-paced Exercises that you should go through and
solve on your own. The only way to learn Python is to do lots of Exercises!
78
[End of Exercise]
You can use the Random Generator in Python. An example of how to use the
Random Generator is shown below:
1 im po rt random
2 f o r x in range (10) :
3 data = random . r a n d i n t ( 1 , 3 1 )
4 p r i n t ( data )
Listing 9.5: Read Data from a File
Make sure to log both the time and the temperature value
You should also plot the data you read from the File.
[End of Exercise]
79
Table 9.1: Logged Data
Time Value
1 22
2 25
3 28
... ...
80
Chapter 10
10.1.2 Exceptions
Even if a statement or expression is syntactically correct, it may cause an error
when an attempt is made to execute it. Errors detected during execution are
called exceptions and are not unconditionally fatal: you will soon learn how to
handle them in Python programs. Most exceptions are not handled by programs,
however, and result in error messages as shown here:
1 >>> 10 ∗ ( 1 / 0 )
2 Traceback ( most r e c e n t c a l l last ) :
3
4 F i l e ”<ipython −i n p u t −2−0b 2 8 0 f 3 6 8 3 5 c >” , l i n e 1 , i n <module>
5 10 ∗ ( 1 / 0 )
6
7 Z e r o D i v i s i o n E r r o r : d i v i s i o n by z e r o
or:
1 >>> ’ 2 ’ + 2
2 Traceback ( most r e c e n t c a l l last ) :
3
81
4 F i l e ”<ipython −i n p u t −3−d2b23a1db757>” , l i n e 1 , i n <module>
5 ’2 ’ + 2
6
7 TypeError : must be s t r , not i n t
• The try block lets you test a block of code for errors.
When an error occurs, or exception as we call it, Python will normally stop and
generate an error message.
1 try :
2 10 ∗ ( 1 / 0 )
3 except :
4 p r i n t ( ”The c a l c u l a t i o n f a i l e d ” )
or:
1 try :
2 print (x)
3 except :
4 p r i n t ( ”x i s not d e f i n e d ” )
The finally block, if specified, will be executed regardless if the try block raises
an error or not.
Example:
82
1 x=2
2
3 try :
4 print (x)
5 e x c e p t NameError :
6 p r i n t ( ”x i s not d e f i n e d ” )
7 except :
8 p r i n t ( ” Something i s wrong ” )
9 finally :
10 p r i n t ( ”The Program i s f i n i s h e d ” )
In general you should use try - except - finally when you try to open a File, read
or write to Files, connect to a Database, etc.
Example:
1 try :
2 f = open ( ” m y f i l e . t x t ” )
3 f . w r i t e ( ”Lorum Ipsum ” )
4 except :
5 p r i n t ( ” Something went wrong when w r i t i n g t o t h e f i l e ” )
6 finally :
7 f . close ()
83
Chapter 11
Debugging in Python
Debuggers are software tools which enable the programmer to monitor the ex-
ecution of a program, stop it, restart it, set breakpoints, and change values in
memory. The term debugger can also refer to the person who is doing the de-
bugging.
As a programmer, one of the first things that you need for serious program
development is a debugger.
Python has a built-in debugger that can be used if you are coding Python with
a basic text editor and running your Python programs from the command line.
A better option is to use the Debugging features integrated in your Python Ed-
itor. Debugging is typically integrated with the Python Editor you are using.
84
Chapter 12
A package contains all the files you need for a module. Modules are Python
code libraries you can include in your project.
Since Python is open source you can find thousands of Python Packages that
you can install and use in your Python programs.
You can use a Python Distribution like Anaconda Distribution (or similar
Python Distributions) to download and install many common Python Pack-
ages as mentioned previously.
If you do not have PIP installed, you can download and install it from this page:
https://pypi.org/project/pip/
PIP is typically used from the Command Prompt (Windows) or Terminal win-
dow (macOS).
1 p i p i n s t a l l packagename
Some Python Editors also have a graphical way of installing Python Packages,
like, e.g., Visual Studio.
85
Part III
86
Chapter 13
Introduction to Python
Environments and
Distributions
Python is open source and everybody can bundle and distribute Python and
different Python Packages.
A Python environment is a context in which you run Python code and includes
Python Packages.
• Anaconda
• Enthought Canopy
• WinPython
• etc.
87
But you can also install the core Python from:
https://www.python.org
Then install the additional Python Packages you need by using PIP.
https://pypi.org/project/pip/
13.1.1 PIP
Web:
https://pypi.org
PIP is typically used from the Command Prompt (Windows) or Terminal win-
dow (macOS).
1 p i p i n s t a l l packagename
13.1.2 Conda
Conda is an open source package management system and environment man-
agement system that runs on Windows, macOS and Linux. Conda installs, runs
and updates packages and their dependencies.
The Conda package and environment manager is included in all versions of Ana-
conda.
Conda was created for Python programs, but it can package and distribute soft-
ware for any language.
Conda allows you to to also create separate environments containing files, pack-
ages and their dependencies that will not interact with other environments.
88
Web:
https://conda.io/
Web:
https://www.anaconda.com
Python Virtual Environments have their own installation directories and they
don’t share libraries with other virtual environments.
Python ”Virtual Environments” is handy when you have different Python appli-
cations that needs different versions of Python or different version of the Python
Packages you are using.
89
Chapter 14
Anaconda
Web:
https://www.anaconda.com
Wikipedia:
https://en.wikipedia.org/wiki/Anaconda( P ythond istribution)
Let say you want to install the Python Control Systems Library package. Just
enter the following in the Anaconda Prompt:
pip i n s t a l l c o n t r o l
90
Figure 14.1: Anaconda Navigator
Python Package Index, or just pip, is a tool used to handle and install Python
packages.
For for information about pip and different packages you can install, see the
following:
https://pypi.org
Figure 14.2 shows where you can find the Anaconda Prompt. Windows: Search
for Anaconda Prompt in the Search field in the start menu.
91
Figure 14.2: Anaconda Navigator
92
Chapter 15
Enthought Canopy
Canopy is freely available to all users under the Canopy license. Canopy pro-
vides access to several hundreds Python packages, including NumPy, SciPy,
Pandas, Matplotlib, and IPython.
Web:
https://www.enthought.com/product/canopy/
93
Part IV
Python Editors
94
Chapter 16
Python Editors
An Editor is a program where you create your code (and where you can run
and test it). Most Editors have also features for Debugging and IntelliSense.
In theory, you can use Windows Notepad for creating Python programs, but
in practice it is impossible to create programs without having an editor with
Debugging, IntelliSense, color formatting, etc.
For simple Python programs you can use the IDLE Editor, but for more ad-
vanced programs a better editor is recommended.
• Spyder
• Visual Studio Code
• Visual Studio
• PyCharm
• Wing
• JupyterNotebook
We will give an overview of these Code Editors in the next chapters.
I guess hundreds of different editors can be used for Python Programming, ei-
ther out of the box or if you install an additional Extension that makes sure
you can use Python in that editor.
If you already have a favorite Code Editor, it is a good change you can use that
one for Python programming.
Which editor you should use depends on your background, what kind of code
editors you have used previously, your programming skills, what your are going
to develop in Python, etc.
95
If you are familiar with MATLAB, Spyder is recommended. Also, if you want
to use Python for numerical calculations and computations, Spyder is a good
choice.
96
Chapter 17
Spyder
97
• Variable Explorer
• etc.
Web:
https://www.spyder-ide.org
If you have used MATLAB previously or want to use Python for scientific use,
Spyder is a good choice. it is easy to install using the Anaconda Distribution.
Web:
https://www.anaconda.com
17.1 Configuration
Typically you want to show figures and plots in separate windows.
98
Figure 17.3: Python Preferences window
99
Chapter 18
Web:
https://code.visualstudio.com
Wikipedia:
https://en.wikipedia.org/wiki/VisualS tudioC ode
100
18.2 Python in Visual Studio Code
In addition to Visual Studio Code you need to install the Python extension for
Visual Studio Code.
You must install a Python interpreter yourself separately from the extension.
For a quick install, use Python from python.org.
https://www.python.org
Python is an interpreted language, and in order to run Python code and get
Python IntelliSense within Visual Studio Code, you must tell Visual Studio
Code which interpreter to use.
Web:
https://code.visualstudio.com/docs/languages/python
101
Chapter 19
Visual Studio
You could say Visual Studio is the big brother of Visual Studio Code.
Visual Studio (from 2017), has integrated support for Python, it is called
”Python Support in Visual Studio”.
Web:
https://visualstudio.microsoft.com
Wikipedia:
https://en.wikipedia.org/wiki/MicrosoftV isualS tudio
102
Figure 19.1: Using Visual Studio as Python Editor
Note that Python support is available only on Visual Studio for Windows. If
you use Mac and Linux, you need to use Visual Studio Code. You could say
Visual Studio Code is a down-scaled version of Visual Studio.
Visual Studio (from 2017), has integrated support for Python, it is called
”Python Support in Visual Studio”. Even if it is integrated, you need to manu-
ally select which components you want to install on your computer. Make sure
to download and run the latest Visual Studio 2017 installer for Windows.
when you run the Visual Studio installer (either for the first time or if you
already have installed Visual Studio 2017 and want to modify it) the window
shown in Figure 19.2 pops up.
The installer presents you with a list of so called workloads, which are groups of
related options for specific development areas. For Python, select the ”Python
development” workload and select Install (Figure 19.3).
103
Figure 19.2: Installing Python Extension for Visual Studio
2 >>> b = 5
3 >>> x = 3
4 >>> y = a ∗x + b
5 >>> y
Start by select from the menu: File - New - Project... The New Project window
pops up. See Figure 19.5.
We can create an ordinary Python Application (one or more Python Scripts),
we can choose to create a Web Application using either Web Frameworks like
Django or Flask, or we can create different Desktop GUI applications. We can
also create Games.
104
Figure 19.4: Python Interactive
We start by creating a basic Hello World Python Application. See Figure 19.1.
Select File - New - Project... The New Project window pops up. See Figure 19.5.
1 p r i n t ( ” H e l l o World” )
Hit F5 (our click the green arrow) in order to run or execute the Python program.
You can also right click on the file and select ”Start without Debugging”.
[End of Example]
1 im po rt m a t p l o t l i b . p y p l o t a s p l t
2 im po rt numpy a s np
3
4 xstart = 0
5 x s t o p = 2∗ np . p i
6 increment = 0.1
7
8 x = np . a r a n g e ( x s t a r t , xstop , i n c r e m e n t )
9
10 y = np . s i n ( x )
11
12 plt . plot (x , y)
13 p l t . t i t l e ( ’ y=s i n ( x ) ’ )
105
Figure 19.5: New Python Project
14 plt . xlabel ( ’x ’ )
15 plt . ylabel ( ’y ’ )
16 plt . grid ()
17 plt . a x i s ( [ 0 , 2∗ np . pi , −1, 1 ] )
18 plt . show ( )
In this example we use the Matplotlib package for plotting, so we need to have
that package installed on the computer. You can install the Matplotlib package
in different Python Environments.
If you haven’t installed the Matplotlib package yet (either as part of Anaconda
or manually using PIP), you can also easily install Python packages from Visual
studio. See Figure 19.8.
You can also easily see which Python Packages that are installed for the differ-
ent Python Environments. See Figure 19.9.
106
Figure 19.6: Python Plotting Example with Visual Studio
The good thing about using Visual Studio is that you have a graphical user
interface for everything, you don’t need to use the Command window etc. for
installing Python Packages, etc.
Hit F5 (our click the green arrow) in order to run or execute the Python program.
You can also right click on the file and select ”Start without Debugging”.
We get the following results, see Figure 19.10.
[End of Example]
107
Figure 19.7: Select your Python Environment
108
Figure 19.9: Installing Python Packages for different Python Environments from
Visual Studio
109
Chapter 20
PyCharm
Web:
https://www.jetbrains.com/pycharm/
Wikipedia:
https://en.wikipedia.org/wiki/PyCharm
Anaconda and JetBrains also have a collaboration and offer what they call Py-
Charm for Anaconda. You can download it here:
110
https://www.jetbrains.com/pycharm/promo/anaconda/
We have code editors like Visual Studio and Visual Studio Code which can be
used for many different programming languages by installing different types of
plugins.
Editors like Spyder and PyCharm are tailor-made editors for the Python lan-
guage.
Spyder is light-weight IDE typically used for scientific use. PyCharm on the
other hand is full-blown IDE for software development in general by using the
Python language. It supports many plugins, it’s easier to program Django, etc.
111
Chapter 21
• Wing 101 – a very simplified free version, for teaching beginning pro-
grammers
• Wing Personal – free version that omits some features, for students and
hobbyists
• Wing Pro – a full-featured commercial (paid) version, for professional
programmers
Web:
https://wingware.com
112
Wikipedia:
https://en.wikipedia.org/wiki/WingI DE
113
Chapter 22
Jupyter Notebook
The Jupyter Notebook is an open-source web application that allows you to cre-
ate and share documents that contain live code, equations, visualizations and
text.
The Notebook has support for over 40 programming languages, including Python.
Web:
http://jupyter.org
Wikipedia:
https://en.wikipedia.org/wiki/ProjectJ upyter
114
22.1 JupyterHub
JupyterHub is a multi-user version of the notebook designed for companies,
classrooms and research labs [17].
Web:
http://jupyter.org/hub
The good thing about Microsoft Azure Notebooks is that you have the infras-
tructure and everything up and running ready for you to use. You can use it
for free as well.
Web:
https://notebooks.azure.com
[End of Example]
115
Figure 22.3: Azure Notebook Project Notebooks
116
Part V
117
Chapter 23
23.1 Introduction
Typically we want to plot the data from the sensor. We can plot save the data
in an array and then plot the data at the end of the program, but more likely
we want to plot one value at the time inside the loop, so-called ”Real-Time
plotting”.
In this chapter we only show how you can plot the data from any given sensor
using this general approach. Instead of the actual sensor data we just use the
random generator in Python.
To read the actual sensor data you typically need a DAQ (Data Acquisition)
device connected to you PC or, e.g, a Raspberry Pi device. In all cases you
will typically need to install a driver from the vendor of the DAQ device or the
sensor you are using.
1 im po rt numpy a s np
2 im po rt m a t p l o t l i b . p y p l o t a s p l t
3
4 p l t . a x i s ( [ 0 , 10 , 0 , 1 ] )
5
6 d e l a y = 1 #Se co n ds
7
8 f o r i in range (10) :
9 y = np . random . random ( )
10 plt . scatter ( i , y)
11 p l t . pause ( d e l a y )
118
12
13 p l t . show ( )
Listing 23.1: Real-Time Plotting in Python
You cannot see the the actual behavior of the plot by watching Figure 23.1, so
you need to run the Python program yourself.
If you run the code you see the plot is updated with a new value every second
as specified in the code.
[End of Example]
Note! If you use Anaconda and Spyder, you typically need to change the the
settings for how graphics are are displayed in Spyder.
Select Preferences from the menu, then IPython console in the list of categories
on the left, then the tab Graphics at the top, and change the Graphics back-end
from Inline to e.g. Automatic or Qt. See Figure 23.2.
119
Figure 23.2: Change how Graphics are displayed in the Spyder Editor
Still in the FuncAnimation() parameters, we set fargs, which are the arguments
we want to pass to our animate function (since we are not calling animate()
directly from within our own code). Then, we set interval, which is how long
we should wait between calls to animate() (in milliseconds).
120
Example 23.3.1. Real-Time Plotting with Animation
Below you find the Python Code for a basic example where we use the anima-
tion module in matplotlib.
In the example we update the plot every seconds by setting the interval=1000ms
as an input argument to the FuncAnaimation function.
1 im po rt d a t e t i m e a s dt
2 im po rt numpy a s np
3 im po rt matplotlib . pyplot as p l t
4 im po rt m at pl ot l ib . animation as animation
5
6 # Create f i g u r e f o r p l o t t i n g
7 fig = plt . figure ()
8 ax = f i g . a d d s u b p l o t ( 1 , 1 , 1 )
9 xs = [ ]
10 ys = [ ]
11
12
13 # This f u n c t i o n i s c a l l e d p e r i o d i c a l l y from FuncAnimation
14 d e f animate ( i , xs , ys ) :
15
16 temp c = round ( np . random . random ( ) , 2 )
17
18 # Add x and y t o l i s t s
19 xs . append ( dt . d a t e t i m e . now ( ) . s t r f t i m e ( ’%H:%M:%S.% f ’ ) )
20 ys . append ( temp c )
21
22 # L i m i t x and y l i s t s t o 20 i t e m s
23 xs = xs [ − 2 0 : ]
24 ys = ys [ − 2 0 : ]
25
26 # Draw x and y l i s t s
27 ax . c l e a r ( )
28 ax . p l o t ( xs , ys )
29
30 # Format p l o t
31 p l t . x t i c k s ( r o t a t i o n =45 , ha= ’ r i g h t ’ )
32 p l t . s u b p l o t s a d j u s t ( bottom =0 .3 0)
33 p l t . t i t l e ( ’ Temperature Data ’ )
34 p l t . y l a b e l ( ’ Temperature ( deg C) ’ )
35
36 # S e t up p l o t t o c a l l animate ( ) f u n c t i o n p e r i o d i c a l l y
37 a n i = a n i m a t i o n . FuncAnimation ( f i g , animate , f a r g s =(xs , ys ) ,
i n t e r v a l =1000)
38 p l t . show ( )
Listing 23.2: Real-Time Plotting with Animation
Figure 23.3 shows the final plot for this example. You cannot see the the actual
behavior of the plot by watching Figure 23.3, so you need to run the Python
program yourself.
[End of Example]
121
Figure 23.3: Real-Time Plotting with Animation
1 im po rt numpy a s np
2 im po rt m a t p l o t l i b . p y p l o t a s p l t
3 im po rt m a t p l o t l i b . a n i m a t i o n a s a n i m a t i o n
4
5 # P ar a m e t e r s
6 x l e n = 200 # Number o f p o i n t s t o d i s p l a y
7 y range = [0 , 20] # Range o f p o s s i b l e Y v a l u e s t o d i s p l a y
8
122
9 # Create f i g u r e f o r p l o t t i n g
10 fig = plt . figure ()
11 ax = f i g . a d d s u b p l o t ( 1 , 1 , 1 )
12 xs = l i s t ( r a n g e ( 0 , 2 0 0 ) )
13 ys = [ 0 ] ∗ x l e n
14 ax . s e t y l i m ( y r a n g e )
15
16
17 # C r e a t e a b l a n k l i n e . We w i l l update t h e l i n e i n animate
18 l i n e , = ax . p l o t ( xs , ys )
19
20 # Add l a b e l s
21 p l t . t i t l e ( ’ Temperature Data ’ )
22 p l t . x l a b e l ( ’ Samples ’ )
23 p l t . y l a b e l ( ’ Temperature ( deg C) ’ )
24
25 # This f u n c t i o n i s c a l l e d p e r i o d i c a l l y from FuncAnimation
26 d e f animate ( i , ys ) :
27
28 r a n d v a l = np . random . random ( ) ∗20 #G e n e r a t e Random V a l u e s
between 0 and 20
29
30 temp c = round ( r a n d v a l , 2 )
31
32 #p r i n t ( temp c )
33
34 # Add y t o l i s t
35 ys . append ( temp c )
36
37 # L i m i t y l i s t t o s e t number o f i t e m s
38 ys = ys [− x l e n : ]
39
40 # Update l i n e with new Y v a l u e s
41 l i n e . s e t y d a t a ( ys )
42
43 return line ,
44
45 # S e t up p l o t t o c a l l animate ( ) f u n c t i o n p e r i o d i c a l l y
46 a n i = a n i m a t i o n . FuncAnimation ( f i g ,
47 animate ,
48 f a r g s =(ys , ) ,
49 i n t e r v a l =100 ,
50 b l i t=True )
51 p l t . show ( )
Listing 23.3: Real-Time Plotting with Animation
Figure 23.4 shows the final plot for this example. You cannot see the the actual
behavior of the plot by watching Figure 23.4, so you need to run the Python
program yourself.
[End of Example]
https://scipy-cookbook.readthedocs.io/items/MatplotlibA nimations.html
123
Figure 23.4: Real-Time Plotting with Animation
Other resources:
https://learn.sparkfun.com/tutorials/graph-sensor-data-with-python-and-matplotlib/allplot-
sensor-data
https://stackoverflow.com/questions/11874767/how-do-i-plot-in-real-time-in-a-while-
loop-using-matplotlib
124
Chapter 24
Here you find more information, resources, videos and examples regarding DAQ:
https://www.halvorsen.blog/documents/technology/daq/
125
Figure 24.1: Data Acquisition (DAQ) System
Web:
http://www.ni.com/
DAQ hardware: WE will use a NI-USB-600x DAQ device from National Instru-
ments, such as:
• NI-USB-6001
• NI-USB-6008
• NI-USB-6009
They are almost identical and the prices is not so bad either.
USB-6008:
http://www.ni.com/en-no/support/model.usb-6008.html
The best way to do this is to use the NI-DAQmx Python API provided by Na-
tional Instruments (nidaqmx). The NI-DAQmx Python API is hosted on
GitHub.
The nidaqmx Python package is a wrapper around the NI-DAQmx C API us-
ing the ctypes Python library, and only supports the Windows operating system.
126
Figure 24.2: USB-6008
For more information about Python Resources for NI Hardware and Software:
ni.com/python
Web:
https://pypi.org/project/PyDAQmx/
https://pythonhosted.org/PyDAQmx/
24.2.1 NI-DAQmx
NI-DAQmx is the software you use to communicate with and control your NI
data acquisition (DAQ) device.
https://www.ni.com/download
127
24.2.2 Measurement Automation Explorer (MAX)
Measurement Automation Explorer (MAX) is a software you can use it to
configure and test the DAQ device before you use it in Python (or other pro-
gramming languages).
With MAX you can make sure your DAQ device works as expected before you
start using it in your Python program. You can use the Test Panels to test your
analog and digital inputs and outputs channels.
You can also change name of the unit, which you need to use in your Python
code.
The nidaqmx Python package is a wrapper around the NI-DAQmx C API us-
ing the ctypes Python library, and only supports the Windows operating system.
128
A Python API for interacting with NI-DAQmx (GitHub):
https://github.com/ni/nidaqmx-python
Other resources:
Control NI DAQ Device with Python and NI DAQmx:
https://knowledge.ni.com/KnowledgeArticleDetails?id=kA00Z0000019Pf1SAE
You can easily extend this examples to make them suit your needs. Typically
you need to include a while loop where you write and/or read from the DAQ
device inside the loop, e.g. read values from one or more sensors that are con-
nected to the DAQ device, you may want to create a control system reading
the process value and then later write the calculated control signal (e.g. using
a PID controller) back to the DAQ device and the process.
Note! The USB-6008 can only output a voltage signal between 0 and 5V.
[End of Example]
129
1 im po rt nidaqmx
2
3 with nidaqmx . Task ( ) a s t a s k :
4 t a s k . a i c h a n n e l s . a d d a i v o l t a g e c h a n ( ”Dev1/ a i 1 ” )
5
6 value = task . read ( )
7 print ( value )
8 task . stop
Listing 24.2: Analog Read using NI DAQ Device
[End of Example]
[End of Example]
[End of Example]
130
24.3.3 Digital Write
Example 24.3.5. Digital Write using NI DAQ Device
Python code:
1 im po rt nidaqmx
2
3 with nidaqmx . Task ( ) a s t a s k :
4 t a s k . d o c h a n n e l s . a d d d o c h a n ( ”Dev1/ p o r t 0 / l i n e 0 ” )
5
6 v a l u e = True
7 task . s t a r t
8 task . write ( value )
9 task . stop
Listing 24.5: Digital Write using NI DAQ Device
[End of Example]
[End of Example]
You should use the ”nidaqmx.stream readers” and nidaqmx.stream writers classes
to increase the performance of your application, which accept pre-allocated
NumPy arrays.
https://nidaqmx-python.readthedocs.io/en/latest/stream readers.html#module-
nidaqmx.stream readers
https://nidaqmx-python.readthedocs.io/en/latest/stream writers.html#module-
nidaqmx.stream writers
131
24.4 Controlling LEDs
In this section we will see how we can control a LED from Python.
Figure 24.6 shows how you wire the LED and connect it to the DAQ device.
132
Figure 24.5: How to wire a LED on a Breadboard
Figure 24.6: Wire the LED and connect to the DAQ device
Below you see an example where we turn the LED on and off inside a loop.
Python code:
1 im po rt nidaqmx
2 im po rt time
3
4
5 with nidaqmx . Task ( ) a s t a s k :
6 t a s k . d o c h a n n e l s . a d d d o c h a n ( ”Dev1/ p o r t 0 / l i n e 0 ” )
7
8 v a l u e = True
9 task . s t a r t
10
11 i = 1
12 while i < 10:
13
133
14 task . write ( value )
15 time . s l e e p ( 1 )
16 v a l u e = not v a l u e
17 task . write ( value )
18 i = i +1
19
20 task . stop
Listing 24.8: Controlling a LED using Python
[End of Example]
• PC with Python
• DAQ device
• Breadboard
We connect the TMP36 to LabVIEW using a USB DAQ Device from National
Instruments, e.g., USB-6001, USB-6008 or similar. I have used a breadboard
for the wiring.
Figure 24.8 show how we can wire the TMP36 together with the USB-6008 DAQ
device.
134
Figure 24.7: TMP36 Temperature Sensor
From the Datasheet (Figure 24.9) we see that there is a linear relationship
between Voltage and degrees Celsius (24.3):
y = ax + b (24.3)
We can find a and b using the following known formula (24.4):
y2 − y1
y − y1 = (x − x1 ) (24.4)
x2 − x1
By putting (24.1) and (24.2) into (24.4) we get:
50 − 25
y − 25 = (x − 0.75) (24.5)
1 − 0.75
Then we get the following formula we can implement in our Python program:
y = 100x − 50 (24.6)
Python code:
135
Figure 24.8: TMP36 tmp36 Wiring
1 im po rt nidaqmx
2 im po rt time
3
4 from nidaqmx . c o n s t a n t s im por t (
5 TerminalConfiguration )
6
7
8 with nidaqmx . Task ( ) a s t a s k :
9 t a s k . a i c h a n n e l s . a d d a i v o l t a g e c h a n ( ”Dev1/ a i 0 ” ,
t e r m i n a l c o n f i g=T e r m i n a l C o n f i g u r a t i o n . RSE)
10
11 i = 0
12 while i < 10:
13
14 v o l t a ge = task . read ( )
15
16 d e g r e e s C = 100∗ v o l t a g e − 50
17
18 p r i n t ( ” Sample : ” , i )
19 p r i n t ( ” V o l t a g e Value : ” , round ( v o l t a g e , 2 ) )
20 p r i n t ( ” C e l s i u s Value : ” , round ( degreesC , 1 ) )
21 p r i n t ( ” \n” )
22 time . s l e e p ( 1 )
23 i = i +1
24
25 task . stop
Listing 24.9: Read TMP36 Temperature Data
In the example an ordinary while loop in combination with the sleep() function
have been used to read one new value each second.
[End of Example]
136
Figure 24.9: TMP3x Datasheet
In this example we will plot the data from the sensor using the Real-time plot-
ting examples shown in Chapter 23.
137
21 task . s t a r t
22
23
24 # This f u n c t i o n i s c a l l e d p e r i o d i c a l l y from FuncAnimation
25 d e f readdaq ( i , xs , ys ) :
26
27 #Read Value from DAQ d e v i c e
28 v o l t a g e = task . read ( )
29
30 #Convert V o l t a g e t o d e g r e e s C e l s i u s
31 d e g r e e s C = 100∗ v o l t a g e − 50
32 temp c = round ( degreesC , 1 )
33 p r i n t ( ” C e l s i u s Value : ” , temp c )
34
35 # Add x and y t o l i s t s
36 xs . append ( dt . d a t e t i m e . now ( ) . s t r f t i m e ( ’%H:%M:%S.% f ’ ) )
37 ys . append ( temp c )
38
39 # L i m i t x and y l i s t s t o 20 i t e m s
40 xs = xs [ − 2 0 : ]
41 ys = ys [ − 2 0 : ]
42
43 # Draw x and y l i s t s
44 ax . c l e a r ( )
45 ax . p l o t ( xs , ys )
46
47 # Format p l o t
48 p l t . x t i c k s ( r o t a t i o n =45 , ha= ’ r i g h t ’ )
49 p l t . s u b p l o t s a d j u s t ( bottom =0 .3 0)
50 p l t . t i t l e ( ’ Temperature Data ’ )
51 p l t . y l a b e l ( ’ Temperature ( deg C) ’ )
52
53
54 # S e t up p l o t t o c a l l readdaq ( ) f u n c t i o n p e r i o d i c a l l y
55 a n i = a n i m a t i o n . FuncAnimation ( f i g , readdaq , f a r g s =(xs , ys ) ,
i n t e r v a l =1000)
56 p l t . show ( )
57 task . stop
Listing 24.10: Real-Time Plotting of Temperature Data
[End of Example]
• PC with Python
• DAQ device
138
• Breadboard
• 10kohm Thermistor
• 10kohm Resistor
• Wires for connecting the components and create the circuit
1
= A + B ln(R) + C(ln(R))3 (24.7)
TK
where A, B and C are constants with the following values: A = 0.001129148, B =
0.000234125, C = 8.76741E − 08
TC = TK − 273.15 (24.9)
Wiring...
Figure 24.10 shows how we wire the components together.
139
Figure 24.11: Voltage Divider
140
where Rt is our 10kohm Thermistor and R0 is an ordinary 10kohm Resistor.
Vin in our case will be +5V which we get from the USB-6008 DAQ device as
shown in the wiring diagram.
1. We wire the circuit on the Breadboard and connect it to the DAQ device
2. We measure Vout using the DAQ
3. We calculate Rt using the Voltage Divider equation
Vout R0
Rt = Vin −Vout
141
24 # Steinhart constants
25 A = 0.001129148
26 B = 0.000234125
27 C = 0.0000000876741
28
29 # S t e i n h a r t −Hart Equation
30 TempK = 1 / (A + (B ∗ np . l o g ( Rt ) ) + (C ∗ pow ( np . l o g ( Rt ) , 3 ) )
)
31
32 # Convert from K e l v i n t o C e l s i u s
33 TempC = TempK − 2 7 3 . 1 5
34
35 p r i n t ( ” Sample : ” , i )
36 p r i n t ( ” V o l t a g e Value : ” , round ( Vout , 2 ) )
37 p r i n t ( ” C e l s i u s Value : ” , round (TempC, 1 ) )
38 p r i n t ( ” \n” )
39 time . s l e e p ( 1 )
40 i = i +1
41
42 task . stop
Listing 24.11: Read Thermistor Temperature Data
[End of Example]
[End of Example]
Here some examples will be shown using a preset temperature sensor from Na-
tional Instruments called NI USB-TC01. This is a USB based temperature
without need for any kind of wiring, you just plug it in and make your Python
program. Since the NI USB-TC01 is compatible with NI-DAQmx, you can pro-
gram it in the same way as other DAQ devices from NI.
142
Figure 24.13: TC-01 Thermocouple Device
1 im po rt nidaqmx
2
3 t a s k = nidaqmx . Task ( )
4
5 t a s k . a i c h a n n e l s . a d d a i t h r m c p l c h a n ( ”TC01/ a i 0 ” )
6
7 task . s t a r t ()
8
9 value = task . read ( )
10 p r i n t ( round ( v a l u e , 1 ) )
11
12 task . stop ()
13 task . c l o s e ()
Listing 24.13: TC-01 Thermocouple Python Example
This is just a basic example, which you can easily extend using a while loop or
using some kind of plotting, etc..
[End of Example]
143
Part VI
Python Database
Development
144
Chapter 25
Here we will learn how we can use Python for communication with a Database
system such as SQL Server or MySQL. We will learn how we connect to a
database, how we can insert data into the database and retrieve data from the
database.
Here you can learn more about Database Systems, download examples and get
additional resources, see videos, etc.:
https://www.halvorsen.blog/documents/technology/database/
145
Figure 25.1: ER Diagram Example
system, like insert data into the database and retrieve data from the database.
Here you can learn more about SQL, download examples and get additional
resources, see videos, etc.:
https://www.halvorsen.blog/documents/technology/database/
25.3 MySQL
Here we will see how we can communicate with a MySQL database from Python.
25.4 MongoDB
Here we will see how we can communicate with a MongoDB database from
Python.
146
Chapter 26
...
147
Chapter 27
pyodbc is an open source Python module that can be used to accessing ODBC
databases.
27.3 pyodbc
pyODBC uses the Microsoft ODBC driver for SQL Server.
148
Note that the ”SQL Server Native Client ...” and earlier drivers are deprecated
and should not be used for new development.
The connection string can be written like this:
1 im po rt pyodbc
2
3 s e r v e r = ”NUCHPH\\SQLEXPRESS”
4 d a t a b a s e = ”BOOKS”
5 username = ” s a ”
6 password = ” xxx ”
7 conn = pyodbc . c o n n e c t ( ”DRIVER={ODBC D r i v e r 17 f o r SQL S e r v e r } ;
SERVER=” + s e r v e r + ” ;DATABASE=” + d a t a b a s e + ” ; UID=” +
username + ” ;PWD=” + password )
8
9 c u r s o r = conn . c u r s o r ( )
10
11 c u r s o r . e x e c u t e ( ”SELECT @@version ; ” )
12 row = c u r s o r . f e t c h o n e ( )
13 w h i l e row :
14 p r i n t ( row [ 0 ] )
15 row = c u r s o r . f e t c h o n e ( )
Listing 27.1: Basic SQL Server Example
Below you find a basic example where data are retrieved from the SQL Server.
1 im po rt pyodbc
2
3 s e r v e r = ”NUCHPH\\SQLEXPRESS”
4 d a t a b a s e = ”BOOKS”
5 username = ” s a ”
6 password = ” xxx ”
7 conn = pyodbc . c o n n e c t ( ”DRIVER={ODBC D r i v e r 17 f o r SQL S e r v e r } ;
SERVER=” + s e r v e r + ” ;DATABASE=” + d a t a b a s e + ” ; UID=” +
username + ” ;PWD=” + password )
8
149
9 c u r s o r = conn . c u r s o r ( )
10
11
12 f o r row i n c u r s o r . e x e c u t e ( ” s e l e c t BookId , T i t l e , I s b n from BOOK” ) :
13 p r i n t ( row . BookId , row . T i t l e , row . I s b n )
Listing 27.2: Getting Data from SQL Server
[End of Example]
27.7 pymssql
Resources:
https://pypi.org/project/pymssql/
http://www.pymssql.org/
27.8 Resources
https://docs.microsoft.com/en-us/sql/connect/python/python-driver-for-sql-server
150
Chapter 28
...
151
Chapter 29
Here we will learn how we can use Python for communication with MongDB.
We will learn how we connect to a database, how we can insert data into the
database and retrieve data from the database.
Python needs a MongoDB driver to access the MongoDB database. Many dif-
ferent drivers do exists, so you just need to choose one.
29.2.1 PyMongo
The PyMongo distribution contains tools for interacting with MongoDB database
from Python
https://pypi.org/project/pymongo/
152
1 python −m p i p i n s t a l l pymongo
153
Part VII
Python Application
Development
154
Chapter 30
Development of
Applications with Python
Python is popular within computation, but can be used within many other
applications and can be integrated and used in combination with other pro-
gramming languages, e.g., for development of Web Applications, etc.
Python can be used for creating Web pages (in combination with HTML, CSS,
JavaScript). Python is then typically used on the server-side, while HTML, CSS
and JavaScript are used on the client-side.
Python can also be used for programming and creating Raspberry Pi applica-
tions.
My list of recommendations:
• Visual Studio and C
• LabVIEW - a graphical programming language well suited for hardware
integration, taking measurements and data logging
155
• Web Programming, such as HTML, CSS, JavaScript and a Server-side
framework/programming language like PHP, ASP.NET
• Databases (such as SQL Server and MySQL) and using the Structured
Query Language (SQL)
• App Development for the 2 main platforms iOS (XCode using the Swift
Programming Language) and Android (Android Studio using the Java
Programming Language or Kotlin Programming language)
If you have skills in most of the tools, programming languages and frameworks
mention above, you are well suited for working as a full-time programmer or
software engineer.
A good resource or starting point for creating Applications for Python is:
In my opinion, tools like Visual Studio where you can create professional GUI
applications using either the C or VB.NET languages in one integrated packages
is a better choice.
Another good alternative is LabVIEW, which has powerful GUI features in com-
bination with extensive hardware integration.
156
For Android development you have Android Studio. Here you can use program-
ming languages like Java and Kotlin.
Since this is a Python textbook, lets go back to the options we have if we want
to create desktop GUI applications with Python.
• PyQt
• Tkinter
• WxPython
• PyGUI
• PySide2
• Kivy
These are just some of the options we have, for a comprehensive overview of
GUI frameworks for Python see the following:
https://docs.python.org/3/library/othergui.htmlother-gui-packages
https://wiki.python.org/moin/GuiProgramming
PyQt and wxPython, all have a modern look and feel and more widgets than
Tkinter.
This is also a bit of a problem when it comes to desktop GUI development with
Python. You have so many choices, and sometimes its better better with one
good option than many half good options.
30.2.1 PyQt
PyQt brings together the Qt C++ cross-platform application framework and the
cross-platform interpreted language Python. Qt is a cross-platform GUI toolkit.
https://riverbankcomputing.com/software/pyqt/intro
https://www.qt.io
157
PyQt Tutorials:
https://likegeeks.com/pyqt5-tutorial/
https://build-system.fman.io/pyqt5-tutorial
30.2.2 PySide2
PySide2 is the official Python module from the Qt for Python project, which
provides access to the complete Qt framework.
The originally PySide framework was originally released by Nokia, then owner
of Qt. After Nokia sold Qt in 2011, PySide was no longer maintained. Then
PySide2 was established and maintained by a community. Finally, in 2016, the
Qt company committed to officially support the PySide2 project.
So basically, PySide2 is very similar to PyQt.
The downside with PySide2 (August 2019) is that it is still in ”beta” (Technical
Preview).
https://pypi.org/project/PySide2/
30.2.3 Tkinter
Another popular GUI framework is Tkinter.
https://docs.python.org/2/library/tkinter.html
30.2.4 WxPython
WxPython is a cross-platform GUI toolkit for the Python language.
https://www.wxpython.org
https://wiki.wxpython.org/Getting
158
30.3 Web Applications
Python can be used for creating Web pages (in combination with HTML, CSS,
JavaScript). Python is then typically used on the server-side, while HTML, CSS
and JavaScript are used on the client-side.
https://www.djangoproject.com
Other popular web application frameworks and programming languages are
ASP.NET and PHP.
https://www.halvorsen.blog/documents/programming/web/
Here you can learn more about Database Systems and SQL, download examples
and get additional resources, see videos, etc.:
https://www.halvorsen.blog/documents/technology/database/
https://www.halvorsen.blog/documents/technology/database/sqls erver.php
30.4.2 MySQL
MySQL is an open-source and widely used Relational Database Management
System (RDBMS).
MySQL comes in different editions, both paid (Enterprise) and free versions
(Community).
159
In addition to the Database itself, the MySQL Workbench is nice to have.
MySQL Workbench visual database design tool, used for Datbase Modelling,
etc. Another handy tool is phpMyAdmin. phpMyAdmin is a free software tool
written in PHP, intended to handle the administration of MySQL.
https://www.halvorsen.blog/documents/technology/database/mysql.php
30.4.3 MariaDB
MariaDB is a spinoff from the more famous MySQL Database System.
The MariaDB database server is published as free and open source software.
MariaDB has compatibility with MySQL in most situations. MariaDB is said
to have slightly better performance than MySQL.
https://www.halvorsen.blog/documents/technology/database/mariadb.php
30.4.4 MongoDB
MongoDB is a general purpose, document-based, distributed database.
160
Chapter 31
Visual Studio (from Visual Studio 2017), has integrated support for Python, it
is called ”Python Support in Visual Studio”.
Web:
https://visualstudio.microsoft.com
Wikipedia:
https://en.wikipedia.org/wiki/MicrosoftV isualS tudio
Here you can learn more about Visual studio and C, download examples and
get additional resources, see videos, etc.:
https://www.halvorsen.blog/documents/programming/csharp/
For an introduction to the Python integration in Visual Studio, see Chapter 19.
161
Chapter 32
https://www.halvorsen.blog/documents/programming/labview/
Her you find information about LabVIEW, you find lots of resources like training
material, videos, code examples, etc.
Web:
http://zone.ni.com/reference/en-XX/help/371361R-01/glang/python pal/
Use the Python functions to call Python code from LabVIEW. See Figure 32.1
Note! LabVIEW supports calling Python version 2.7 and 3.6. Although un-
supported versions might work with the LabVIEW Python functions, NI rec-
ommends using supported versions of Python only.
Ensure that the bitness of Python corresponds to the bitness of LabVIEW in-
stalled on the machine. This means if you have LabVIEW 32 bit, you should
use Python 32 bit and if you have LabVIEW 64 bit, you should use Python 64
162
bit.
To run the Python code, LabVIEW requires the Python shared libraries (DLLs)
in the system path.
For Windows: If you install Python 3.6, add the directory containing python36.dll
to the system path. If you install Python 2.7, add the directory containing
python27.dll to the system path.
For detailed instructions regarding Installing Python for Calling Python Code:
http://www.ni.com/product-documentation/54295/en/
LabVIEW functions for dealing with Python: Open Python Session Python
Node Close Python Session
Here I will present some examples how we can integrate an existing Python
script or Python function.
Example 32.2.1. Python Integration in LabVIEW
We want to use Python to covert between Ceslius and Fahrenheit (and vice
versa).
163
3 Tf = ( Tc ∗ 9 / 5 ) + 32
4 r e t u r n Tf
5
6
7 d e f f 2 c ( Tf ) :
8
9 Tc = ( Tf − 3 2 ) ∗ ( 5 / 9 )
10 r e t u r n Tc
Listing 32.1: Python Functions
Then, we create a Python script for testing the functions (testf ahrenheit.py) :
1 from f a h r e n h e i t import c2f , f2c
2
3 Tc = 0
4
5 Tf = c 2 f ( Tc )
6
7 p r i n t ( ” F a h r e n h e i t : ” + s t r ( Tf ) )
8
9
10 Tf = 32
11
12 Tc = f 2 c ( Tf )
13
14 p r i n t ( ” C e l s i u s : ” + s t r ( Tc ) )
Listing 32.2: Testing the Functions
Lets make the LabVIEW program that call these Python functions:
In Figure 32.4 we see LabVIEW Code for calling both Python func-
tions (c2f and f2c) from LabVIEW.
[End of Example]
164
Figure 32.2: Python Integration in LabVIEW
165
Figure 32.4: Python Integration in LabVIEW
166
Chapter 33
https://www.halvorsen.blog/documents/technology/iot/raspberry pi.php
Other Resources:
https://learn.sparkfun.com/tutorials/python-programming-tutorial-getting-started-
with-the-raspberry-pi/programming-in-python
First, before you start programming Python on a Raspberry Pi device, you need
to install an operating system like Raspbian. Raspbian is a Linux distribution
tailor made for Raspberry Pi.
https://www.raspberrypi.org/downloads/raspbian/
167
Chapter 34
• HTML
• CSS
• JavaScript
Here you find more information, resources, videos and examples regarding Web
Development:
https://www.halvorsen.blog/documents/programming/web/
34.1.1 HTML
Here you find more information, resources, videos and examples regarding HTML:
https://www.halvorsen.blog/documents/programming/web/html.php
34.1.2 CSS
34.1.3 JavaScript
• HTML
• CSS
• JavaScript
168
In addition you typically need a Web Framework for creating dynamic web pages
that communicate with a Database, etc.
• PHP
• ASP.NET
• ... Many others, including different Python Web Development Frameworks
34.2.1 PHP
Here you find more information, resources, videos and examples regarding PHP:
https://www.halvorsen.blog/documents/programming/web/php.php
34.2.2 ASP.NET
Here you find more information, resources, videos and examples regarding ASP.NET:
https://www.halvorsen.blog/documents/programming/web/aspn et.php
There are different Python Frameworks you can use for creating Web Applica-
tions with Python.
Django Bottle Flask
169
Chapter 35
Here are some programming environments and programming languages for cre-
ating GUI applications presented.
35.1 LabVIEW
Here you find more information, resources, videos and examples regarding Lab-
VIEW:
https://www.halvorsen.blog/documents/programming/labview/
Here you find more information, resources, videos and examples regarding HTML:
https://www.halvorsen.blog/documents/programming/web/html.php
Here you find more information, resources, videos and examples regarding PHP:
https://www.halvorsen.blog/documents/programming/web/php.php
Here you find more information, resources, videos and examples regarding ASP.NET:
https://www.halvorsen.blog/documents/programming/web/aspn et.php
170
Chapter 36
171
Part VIII
172
Chapter 37
37.1 Introduction
PyQt brings together the Qt C++ cross-platform application framework and
the cross-platform interpreted language Python.
37.2 Introduction to Qt
Qt (pronounced ”cute”) is a free and open-source widget toolkit for creating
graphical user interfaces as well as cross-platform applications that run on vari-
ous software and hardware platforms such as Linux, Windows, macOS, Android
or embedded systems with little or no change in the underlying codebase while
still being a native application with native capabilities and speed.
If you want to use Qt inside Python you will need a Python library that let you
interface with Qt’s C++ API. Many such bindings/libraries do exist. The most
used Qt Python library is PyQt. We will use PyQt in this chapter.
The originally PySide framework was originally released by Nokia, then owner
of Qt. After Nokia sold Qt in 2011, PySide was no longer maintained. Then
173
PySide2 was established and maintained by a community. Finally, in 2016, the
Qt company committed to officially support the PySide2 project.
So basically, PySide2 is very similar to PyQt.
The downside with PySide2 (August 2019) is that it is still in ”beta” (Technical
Preview).
Wikipedia:
https://en.wikipedia.org/wiki/Qt( sof tware)
https://likegeeks.com/pyqt5-tutorial/
https://build-system.fman.io/pyqt5-tutorial
https://data-flair.training/blogs/python-pyqt5-tutorial/
https://www.guru99.com/pyqt-tutorial.html
https://pythonspot.com/gui/
37.3.1 PyQtChart
PyQt don’t include any types of charts. In order to use charts or plotting, you
can use PyQtChart.
174
https://www.riverbankcomputing.com/software/pyqtchart/
The Python Package Index (PyPI) is a repository of software for the Python
programming language. Package authors use PyPI to distribute their software.
https://packaging.python.org/tutorials/installing-packages/
For more information about PyPI:
https://pypi.org
https://pypi.org/project/PyQt5/
You can download and install the Qt Designer from this web site:
https://build-system.fman.io/qt-designer-download
175
Figure 37.1: Qt Designer
1 im po rt s y s
2 from PyQt5 . QtWidgets imp ort Q A p p l i c a t i o n , QWidget
3 if name == ” m a i n ” :
4 a p p l i c a t i o n = QApplication ( sys . argv )
5 window = QWidget ( )
6 window . r e s i z e ( 3 0 0 , 2 0 0 )
7 window . s e t W i n d o w T i t l e ( ” H e l l o World” )
8 window . show ( )
9 sys . exit ( application . exec () )
Listing 37.1: Basic PyQt Application
If you are using macOS, the Python code above gives the basic application
shown in Figure 37.2.
If you are using Windows, the Python code above gives the basic application
shown in Figure 37.3.
For the first, with the same Python code we can create cross-platform applica-
tion.
This statement imports all the necessary modules you need to create your GUI.
176
Figure 37.2: Basic PyQt Application on macOS
The QtWidgets module contains all the major widgets that you will be using in
this tutorial.
1 a p p l i c a t i o n = QApplication ( sys . argv )
The first thing you need to create is an object of the QApplication class. All
PyQt GUI application must create an instance of QApplication.
sys.argv is the list of command-line parameters that you can pass to the appli-
cation when launching it through the shell or while automating the interface.
If you don’t need to pass any arguments to QApplications, you can use [].
1 a p p l i c a t i o n = QApplication ( [ ] )
Then we need to create an object of the QWidget class. QWidget is the foun-
dation for all UI objects in Qt. Typically, everything you see in an an PyQt
application is a widget, examples: Label, ComboBox, CheckBox, RadioButton,
PushButton, etc.
1 window = QWidget ( )
1 window . r e s i z e ( 3 0 0 , 2 0 0 )
The resize method of the QWidget class allows you to set the dimensions of any
widget. In this case, you have resized the window to 300px by 200px.
Note that widgets could be nested together, the outermost widget (i.e., the wid-
get with no parent) is called a Window.
177
Figure 37.3: Basic PyQt Application on Windows
1 window . s e t W i n d o w T i t l e ( ” H e l l o World” )
When all the settings are done, we need to show the window on the screen by
using the show() method:
1 window . show ( )
The app.exec () method starts the event loop inside Qt/C++. PyQt is mainly
written in C++ and uses the event loop mechanism to implement parallel exe-
cution. app.exec () passes the control over to Qt which will exit the application
only when the user closes it from the GUI.
178
1 im po rt s y s
2 from PyQt5 . QtWidgets imp ort Q A p p l i c a t i o n , QWidget , QLabel
3 if name == ” m a i n ” :
4 a p p l i c a t i o n = QApplication ( sys . argv )
5 window = QWidget ( )
6 window . r e s i z e ( 3 0 0 , 2 0 0 )
7 window . s e t W i n d o w T i t l e ( ” H e l l o World” )
8
9 l a b e l = QLabel ( window )
10 l a b e l . s e t T e x t ( ” This i s a L a b e l ” )
11 l a b e l . move ( 1 0 0 , 5 0 )
12
13 window . show ( )
14 sys . exit ( application . exec () )
Listing 37.2: QLabel Example
[End of Example]
179
11 inputbox . r e s i z e (200 , 20)
12 i n p u t b o x . move ( 2 0 , 5 0 )
13
14 window . show ( )
15 sys . exit ( application . exec () )
Listing 37.3: QLineEdit EXample
[End of Example]
180
This gives the window as shown in Figure 37.6.
[End of Example]
Example:
1 s e l f . btnShowData . c l i c k e d . c o n n e c t ( s e l f . b t n S h o w D a t a c l i c k e d )
You need to define a function that is called when the signal occurs. This func-
tion is called a slot in PyQt.
Example:
1 def btnShowData clicked ( s e l f ) :
2 temp = np . random . r a n d i n t ( 2 0 , 5 0 )
3 s e l f . txtTemp . s e t T e x t ( s t r ( temp ) )
181
1 im po rt s y s
2 from PyQt5 . QtWidgets imp ort Q A p p l i c a t i o n , QWidget , QPushButton
3
4 def button clicked () :
5 p r i n t ( ”You c l i c k e d t h e Button ” )
6
7 if name == ” m a i n ” :
8 a p p l i c a t i o n = QApplication ( sys . argv )
9 a p p l i c a t i o n . s e t S t y l e ( ’ Fusion ’ )
10 window = QWidget ( )
11 window . r e s i z e ( 3 0 0 , 2 0 0 )
12 window . s e t W i n d o w T i t l e ( ” H e l l o World” )
13
14 b ut to n = QPushButton ( window )
15 b ut to n . s e t T e x t ( ” C l i c k Me” )
16 b ut to n . move ( 1 0 0 , 5 0 )
17 b ut to n . c l i c k e d . c o n n e c t ( b u t t o n c l i c k e d )
18
19 window . show ( )
20 sys . exit ( application . exec () )
Listing 37.5: Button Click
[End of Example]
182
Figure 37.7: QMessageBox Example
[End of Example]
183
32
33 name = s e l f . txtName . t e x t ( )
34 t e x t = ” I s your Name ” + name + ” ? ”
35 r e p l y = QMessageBox . q u e s t i o n ( s e l f , ’ Message ’ , t e x t ,
QMessageBox . Yes | QMessageBox . No , QMessageBox . No)
36
37 i f r e p l y == QMessageBox . No :
38 s e l f . txtName . s e t T e x t ( ” P l e a s e e n t e r your Name” )
39
40
41 if name == ’ m a i n ’ :
42 app = Q A p p l i c a t i o n ( s y s . a r g v )
43 app . s e t S t y l e ( ’ F u s i o n ’ )
44 window = A p p l i c a t i o n ( )
45 s y s . e x i t ( app . e x e c ( ) )
Listing 37.7: Combining different Widgets and Event Handling Example
[End of Example]
184
Some examples are:
• Logging Data from a Sensor and presenting the values on the screen
• Simulation of a system and presenting values on the screen
• Control System
• etc.
...
1 ...
2 ...
Listing 37.9: xxx
185
Part IX
Resources
186
Chapter 38
Python Resources
SciPy Library:
https://www.scipy.org
Matplotlib Library:
https://matplotlib.org
187
Visual studio Code:
https://code.visualstudio.com
Visual Studio:
https://visualstudio.microsoft.com
PyCharm:
https://www.jetbrains.com/pycharm/
Wing:
https://wingware.com
Jupyter Notebook:
http://jupyter.org
188
Bibliography
189
[18] python.org, “Applications for python -
https://www.python.org/about/apps/,” 2018.
190
Part X
Solutions to Exercises
191
Start using Python
Create a Script in Python (.py file) where you plot the solution x(t) in the time
interval:
0 ≤ t ≤ 25
Add Grid, and proper Title and Axis Labels to the plot.
Python Script:
1 im po rt math a s mt
2 im po rt numpy a s np
3 im po rt m a t p l o t l i b . p y p l o t a s p l t
4
5
6 # Model P a r a m e t e r s
7 T = 5
8 a = −1/T
9
10 # Simulation Parameters
11 x0 = 1
12 t = 0
13
14 tstart = 0
192
15 t s t o p = 25
16
17 increment = 1
18
19 x = []
20 x = np . z e r o s ( t s t o p +1)
21
22 t = np . a r a n g e ( t s t a r t , t s t o p +1 , i n c r e m e n t )
23
24
25 # Define the Function
26 f o r k in range ( tstop ) :
27 x [ k ] = mt . exp ( a ∗ t [ k ] ) ∗ x0
28
29
30 # Plot the Simulation Results
31 plt . plot (t , x)
32 p l t . t i t l e ( ’ S i m u l a t i o n o f Dynamic System ’ )
33 plt . xlabel ( ’ t ’ )
34 plt . ylabel ( ’x ’ )
35 plt . grid ()
36 p l t . a x i s ( [ 0 , 25 , 0 , 1 ] )
37 p l t . show ( )
[End of Exercise]
193
Mathematics in Python
[End of Solution]
ln (ax2 + bx + c) − sin(ax2 + bx + c)
f (x) = (4)
4πx2 + cos(x − 2)(ax2 + bx + c)
194
Given a = 1, b = 3, c = 5 Find f (9)
(The answer should be f (9) = 0.0044)
Tip! You should split the expressions into different parts, such as:
poly = ax2 + bx + c
num = . . .
den = . . .
f = ...
This makes the expression simpler to read and understand, and you minimize
the risk of making an error while typing the expression in Python.
When you got the correct answer try to change to, e.g., a = 2, b = 8, c = 6
Find f (9)
Python Script:
1 ...
[End of Solution]
195
Discrete Systems
Bacteria Population
In this task we will simulate a simple model of a bacteria population in a jar.
ẋ = bx − px2 (7)
We will simulate the number of bacteria in the jar after 1 hour, assuming that
initially there are 100 bacteria present.
Find the discrete model using the Euler Forward method by hand and imple-
ment and simulate the system in Python using a For Loop.
xk+1 − xk
ẋ ≈ (8)
Ts
Ts - Sampling Interval
Then we get:
196
xk+1 − xk
= bxk − px2k (9)
Ts
Python Script:
1 # Simulation of Bacteria Population
2 im po rt numpy a s np
3 im po rt m a t p l o t l i b . p y p l o t a s p l t
4
5 # Model P a r a m e t e r s
6 b = 1
7 p = 0.5
8
9 # Simulation Parameters
10 Ts = 0 . 0 1
11 Tstop = 1
12 xk = 100
13 N = i n t ( Tstop /Ts ) # S i m u l a t i o n l e n g t h
14 data = [ ]
15 data . append ( xk )
16
17
18 # Simulation
19 f o r k i n r a n g e (N) :
20 xk1 = xk + Ts∗ ( b ∗ xk − p ∗ xk ∗ ∗ 2 ) ;
21 xk = xk1
22 data . append ( xk1 )
23
24 # Plot the Simulation Results
25 t = np . a r a n g e ( 0 , Tstop+Ts , Ts )
26
27 plt . p l o t ( t , data )
28 plt . t i t l e ( ’ Simulation of Bacteria Population ’ )
29 plt . xlabel ( ’ t [ s ] ’ )
30 plt . ylabel ( ’x ’ )
31 plt . grid ()
32 plt . axis ([0 , 1 , 0 , 100])
33 plt . show ( )
[End of Solution]
197
Figure 2: Simulation of Bacteria Population
dx1
= −x2 (11)
dt
dx2
= x1 (12)
dt
Find the discrete system and simulate the discrete system in Python. Solve the
equations, e.g., in the time span [-1 1] with initial values [1, 1].
Python Script:
1 # S i m u l a t i o n with 2 V a r i a b l e s
2 im po rt numpy a s np
3 im po rt m a t p l o t l i b . p y p l o t a s p l t
4
5 # Model P a r a m e t e r s
6 b = 1
7 p = 0.5
8
9 # Simulation Parameters
10 Ts = 0 . 1
11 T s t a r t = −1
12 Tstop = 1
13 x1k = 1
14 x2k = 1
15 N = i n t ( ( Tstop−T s t a r t ) /Ts ) # S i m u l a t i o n l e n g t h
16 datax1 = [ ]
198
17 datax2 = [ ]
18 datax1 . append ( x1k )
19 datax2 . append ( x2k )
20
21
22 # Simulation
23 f o r k i n r a n g e (N) :
24 x1k1 = x1k − Ts ∗ x2k
25 x2k1 = x2k + Ts ∗ x1k
26
27 x1k = x1k1
28 x2k = x2k1
29 datax1 . append ( x1k1 )
30 datax2 . append ( x2k1 )
31
32 # Plot the Simulation Results
33 t = np . a r a n g e ( T s t a r t , Tstop+Ts , Ts )
34
35 plt . p l o t ( t , datax1 , t , datax2 )
36 plt . t i t l e ( ’ S i m u l a t i o n with 2 V a r i a b l e s ’ )
37 plt . xlabel ( ’ t [ s ] ’ )
38 plt . ylabel ( ’x ’ )
39 plt . grid ()
40 plt . a x i s ( [ − 1 , 1 , −1.5 , 1 . 5 ] )
41 plt . show ( )
Alternative Solution:
1 # S i m u l a t i o n with 2 V a r i a b l e s
2 im po rt numpy a s np
3 im po rt m a t p l o t l i b . p y p l o t a s p l t
4
5 # Model P a r a m e t e r s
199
6 b = 1
7 p = 0.5
8
9 # Simulation Parameters
10 Ts = 0 . 1
11 T s t a r t = −1
12 Tstop = 1
13 N = i n t ( ( Tstop−T s t a r t ) /Ts ) # S i m u l a t i o n l e n g t h
14 x1 = np . z e r o s (N+2)
15 x2 = np . z e r o s (N+2)
16 x1 [ 0 ] = 1
17 x2 [ 0 ] = 1
18
19
20 # Simulation
21 f o r k i n r a n g e (N+1) :
22 x1 [ k +1] = x1 [ k ] − Ts ∗ x2 [ k ]
23 x2 [ k +1] = x2 [ k ] + Ts ∗ x1 [ k ]
24
25
26 # Plot the Simulation Results
27 t = np . a r a n g e ( T s t a r t , Tstop+2∗Ts , Ts )
28
29 plt . p l o t ( t , x1 , t , x2 )
30 plt . t i t l e ( ’ S i m u l a t i o n with 2 V a r i a b l e s ’ )
31 plt . xlabel ( ’ t [ s ] ’ )
32 plt . ylabel ( ’x ’ )
33 plt . grid ()
34 plt . a x i s ( [ − 1 , 1 , −1.5 , 1 . 5 ] )
35 plt . show ( )
Choose the approach that fits you. You should also check the time that the
simulation take. For larger simulations, this second alternative may be better.
[End of Solution]
200
Python for Software Development