Python Programming
Python Programming
Programming
Hans-Petter Halvorsen
https://www.halvorsen.blog
Python Programming
Python Programming
Hans-Petter Halvorsen
2019
Python Programming
c Hans-Petter Halvorsen
ISBN:978-82-691106-4-7
Preface
Python is a popular programming language, and it is one of the most used
programming languages today.
Python works on all the main platforms and operating systems used today, such
Windows, macOS, and Linux.
1
Here you find my Web page with Python resources:
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.
Python Books
You find other Python textbooks within different domains on my Python Web
page: https://www.halvorsen.blog/documents/programming/python/
Python Books:
2
calculations in mathematics and engineering. Necessary theory is
presented in addition to many practical examples.
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 socalled
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.
3
• Planning
• Requirements Analysis
• Design
• Implementation
• Testing
4
Contents
I Getting Started with Python 10
1 Introduction 11
1.2 MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2 What is Python? 17
5
2.1 Introduction to Python ....................... 17
2.3 Anaconda . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
2.4.3 Spyder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
2.4.5 PyCharm . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
2.5 Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
6
3.5.3 Run Python Scripts from the Command Prompt in Win-
dows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
4.2 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
4.2.1 Numbers. . . . . . . . . . . . . . . . . . . . . . . . . . . 38
4.2.2 Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
4.6.1 Subplots . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
4.6.2 Exercises. . . . . . . . . . . . . . . . . . . . . . . . . . . 49
II Python Programming 50
5 Python Programming 51
5.2 Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
5.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
6.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
7
6.3 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
7.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
7.3 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
8.2 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
9.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
9.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
11 Debugging in Python 82
13.1.2 Conda . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
8
14 Anaconda 88
15 Enthought Canopy 90
IV Python Editors 91
16 Python Editors 92
17 Spyder 94
19 Visual Studio 98
VI Resources 128
24 Python Resources129
24.1 Python Distributions . . . . . . . . . . . . . . . . . . . . . . . . . 129
9
24.2 Python Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
24.3 Python Editors . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
24.4 Python Tutorials . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
24.5 Python in Visual Studio . . . . . . . . . . . . . . . . . . . . . . . 130
10
Part I
11
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 socalled
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.
12
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.
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
Language in 2018. See Figure 1.2
As we see in Figure 1.2 they categorize the different Programming Languages
into the following categories:
• Web
13
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
Applications, 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.
Lets summarize:
• Python is fun to learn and use and it is also named after the British comedy
group called Monty Python.
14
• Python has a simple and flexible code structure and the code is easy to
read.
• Python is highly extendable due to its high number of free available Python
Packaged and Libraries
15
• Python - Numerical calculations, and Scientific computing, etc.
• 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/
16
Figure 1.5: The Future of Python
Chapter 2
What is Python?
2.1 Introduction to Python
Python is an open source and cross-platform programming language, that has
become increasingly popular over the last ten years. It was first released in 1991.
Latest version is 3.7.0. CPython is the reference implementation of the Python
programming language. Written in C, CPython is the default and most widely-
used implementation of the language.
17
The programming language is maintained and available from (Python Software
Foundation): 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
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 install
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.
18
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.
With interpreted languages, the code is saved in the same format that you
entered. 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.
19
Thus, an interpreted language is generally more suited for doing ”ad hoc”
calculations 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.
Lots of Python packages exists, depending on what you are going to solve. We
have Python packages for Desktop GUI Development, Database Development,
Web Development, Software Development, etc.
See also the Python Package Index (PyPI) web site: https://pypi.org
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.
• SciPy - SciPy is a free and open-source Python library used for scientific
computing and technical computing. SciPy contains modules for
optimization, linear algebra, integration, interpolation, special functions,
20
FFT, signal and image processing, ODE solvers and other tasks common in
science and engineering. [9]
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.
Web:
https://www.anaconda.com
Wikipedia: https://en.wikipedia.org/wiki/Anaconda(Pythondistribution)
Spyder and the Python packages (NumPy, SciPy, Matplotlib, ...) mention above ++
+ are included in the Anaconda Distribution.
21
• Wing Python IDE
• Jupyter Notebook
These editors are shortly described below and in more detail later in this
textbook.
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
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(software)
22
Visual studio is available for Windows and macOS.
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 isualStudio
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.
Web:
https://www.jetbrains.com/pycharm/
• Wing Personal – free version that omits some features, for students and
hobbyists
Web:
http://jupyter.org
Wikipedia:
https://en.wikipedia.org/wiki/ProjectJupyter
23
2.5 Resources
Here are some useful Python resources:
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 basic
Python programming this is good enough.
For more advanced Python Programming you typically need a better Code Editor
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.
24
In order to install the Microsoft Store version of Python just open Microsoft Store
in Windows 10 and search for Python.
25
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.
26
[End of Example]
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.
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.
27
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:
Just type python at your console, hit Enter, and you should enter Python’s
Interpreter.
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:
>>> a = 5 >>> b = 2
>>> x = 5
>>> y = 3∗a + b
>>> y
28
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 select ”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.
29
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.
C:\ Users\user\AppData\Local\Programs\Python\Python37−32\
Click Save and open the Command Prompt once more and enter ”python” to
verify it works. See Figure 3.3.
30
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.
31
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 /Users/username/Downloads
2 $ python helloworld . 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 are you?
32
Figure 3.7: Python Script
1 > cd /
2 > cd Temp
3
> python helloworld . 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 are 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.
33
Figure 3.9: Running Python Scripts from Console window on macOS
34
Chapter 4
[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.
Python
We use the basic IDLE (or another Python Editor) and type the following:
1 >>> x = 3
2 >>> x
3
3
35
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]
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.
36
Figure 4.1: Basic Python
• A variable name can only contain alpha-numeric characters (A-z, 0-9) and
underscores
• Variable names are case-sensitive, e.g., amount, Amount and AMOUNT are
three different variables.
4.2.1 Numbers
There are three numeric types in Python:
• int
• float
• complex
Variables of numeric types are created when you assign a value to them, so in
normal coding you don’t need to bother.
This means you just assign values to a variable without worrying about what
kind of data type it is.
1 print ( type (x) ) print (
2 type (y) ) print ( type (z) )
3
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 = ”Hello World ! ”
2
3 print (a)
4
5
print (a [1]) print (a [ 2
6
: 5 ] ) print ( len (a) )
7
print (a . lower () )
8
9 print (a . upper () ) print (a . replace
10 (”H” , ”J”) ) print (a . split (” ”) )
11
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.
38
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]
The following example asks for the user’s name, then, by using the input()
method, the program prints the name to the screen:
1 print (”Enter your name: ”)
2 x = input ()
3
print (”Hello , ” + x)
[End of Example]
In another chapter we will learn to create our own functions from scratch.
39
The math module has all the basic math functions you need, such as:
Trigonometric functions: sin(x), cos(x), etc. Logarithmic functions: log(), log10(),
etc. Constants like pi, e, inf, nan, etc. etc.
x = 3.14 y =
sin (x)
print (y)
If we need only the sin() function we can do like this:
1
2
3
4
5
6
x = 3.14y
= sin (x) print (y)
y = cos
(x)print (y)
x =
3.14y = sin (x)
print (y)
y = cos
(x)print (y)
40
2
3
4
5
6
7
8
import math
[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
packages. 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
41
4.5 Using Python Libraries, Packages and Modules
Rather than having all of its functionality built into its core, Python was designed
to be highly extensible. This approach has advantages and disadvantages. An
disadvantage is that you need to install these packages separately and then later
import these modules in your code.
• SciPy - SciPy is a free and open-source Python library used for scientific
computing and technical computing. SciPy contains modules for
optimization, linear algebra, integration, interpolation, special functions,
FFT, signal and image processing, ODE solvers and other tasks common in
science and engineering.
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.
In this example we use both the math module in the Python Standard Library
and the NumPy library:
1 import math as mt import
2 numpy as np
3
4
x =3
print (y)
5
6
7
8
9
10
11
12
13
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 import ∗ from
2 numpy import ∗
3
4
x=3
5
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/
43
4.6 Plotting in Python
Typically you need to create some plots or charts. In order to make plots or
charts in Python you will need an external library. The most used library is
Matplotlib.
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 import matplotlib . pyplot as plt
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:
44
9
10
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.
[End of Example]
• plot()
• xlabel()
• ylabel()
45
• show()
46
14
15
[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.
47
1 import matplotlib . pyplot as plt import numpy as np
2
3 xstart = 0
4 xstop = 2∗np. pi increment = 0.1 x = np. arange
5
6 ( xstart , xstop , increment ) y = np. sin (x) z = np. cos
7
8
(x)
9
10
11
plt . subplot (2 ,1 ,1) plt . plot
12 (x , y , ’g ’ ) plt . t i t l e ( ’ sin ’
13 ) plt . xlabel ( ’x ’ ) plt . ylabel
14 ( ’ sin (x) ’ ) plt . grid () plt .
15 show()
16
17
18 plt . subplot (2 ,1 ,2) plt . plot
19 (x , z , ’ r ’ ) plt . t i t l e ( ’ cos ’
20
) plt . xlabel ( ’x ’ ) plt . ylabel
21
( ’ cos (x) ’ ) plt . grid () plt .
22
show()
23
24
25
26
27
28
29
30
[End of Example]
48
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]
Part II
Python Programming
49
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 features
should be familiar and known to you. All programming languages has these
features built-in, but the syntax is slightly different from one language to another.
Using If - Else:
1 a=5b=
2 8
3
if a > b:
print (”a is greater than b”)
else : 50
print (”b is greater than a or a and b are equal”)
4
5
6
7
Using Elif:
1 a=5b=
2 8
3
4 if a > b:
5
print (”a is greater than b”)
6
7
elif b>a:
8 print (”b is greater than a”)
9 e l i f a == b:
print (”a is equal to b”)
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:
print (N)
51
for x in data : print (x)
23
24
25
26
27
You can return the number of elements in the array like this:
1 N = len ( data )
You can get a specific value inside the array like this:
1 index = 2 x = cars
2 [ 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.
Below you see a basic example how you can use a For loop in Python:
1 for i in range (1 , 10) : print ( i )
2
52
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.
Finally, you can also use the range() function like this:
1 start = 4
2 stop = 12 #but not including step = 2
3
4
for x in range ( start , stop , step ) : print (x)
5
6
You should try all these examples in order to learn the basic structure of a For
loop.
[End of Example]
You typically want to use a For loop for find the sum of a given data set.
53
1 data = [1 , 5 , 6 , 3 , 12 , 3] sum = 0
2
3 #Find the Sum of all the numbers for x
4
in data :
5
sum = sum + x
6
7
8
print (sum)
9
10 #Find the Mean or Average of all the numbers N = len ( data )
11
12 mean = sum/N
13
14 print (mean)
15
16
17
[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.
54
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 fib2 = 1
4
5 print ( fib1 ) print
6
( fib2 )
7
8
for k in range (N−2) :
9
10
fib next = fib2 +fib1 fib1 =
11 fib2 fib2 = fib next print ( fib
12 next )
13
Alternative solution:
1 N = 10 fib = [0 ,
2
3 1]
4
5
6
for k in range (N−2) : fib next = fib [ k+1]
7
+fib [ k ] fib . append( fib next ) print ( fib )
8
9
10
N = 10
print ( fib )
4
5
6
7
8
9
10
11
12
13
14
15
[End of Example]
Simple example:
1 for i in range (1 , 10) :
2
for k in range (1 , 10) :
3
print ( i , k)
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.
56
Tip! I guess this can be done in many different ways, but one way is to use 2
nested For Loops.
[End of Exercise]
[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!
57
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]
58
Chapter 6
If you are familiar with one or more other programming language, creating and
using functions should be familiar and known to you. All programming languages
has the possibility to create functions, but the syntax is slightly different from
one language to another.
Scripts:
Functions:
• Have a separate workspace and internal variables that is only valid inside
the function
• Your own user-defined functions work the same way as the built-in
functions 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:
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 def add(x , y) :
[End of Example]
60
Listing 6.3: Function calculating the Average
Next, we create a new Python File (e.g., testaverage.py) where we use the
function we created:
1 from myfunctions import average
2
3 a=2b=
4 3
5
6 c = average (a ,b) print (c)
7
8
[End of Example]
Example 6.2.1. Create a Function Function with multiple return values Create
61
[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:
2π[radians] = 360[degrees] (6.1)
This gives:
(6.2)
and
(6.3)
Create two functions that convert from radians to degrees (r2d(x)) and from
degrees to radians (d2r(x)) respectively.
[End of Exercise]
62
They also appear in biological settings, such as branching in trees, arrangement
of leaves on a stem, the fruitlets of a pineapple, the flowering of artichoke, an
uncurling fern and the arrangement of a pine cone.
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.
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
checkifprime (number)
63
2
[End of Exercise]
64
Chapter 7
The foundation for all object oriented programming (OOP) languages are Classes.
1 class Car :
2 model = ”Volvo”
3
color = ”Blue”
4
5
6
car = Car()
7
8
9
print ( car . model) print
10
( car . color )
Listing 7.1: Simple Python Class
Volvo
Blue
This example don’t illustrate the good things with classes so we will create some
more examples.
65
[End of Example]
[End of Example]
We will create a simple example where we use the init () function to illustrate the
principle.
66
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 Function
(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:
1 car1 = Car(”Tesla” , ”Red”)
67
[End of Example]
We start by creating the Class and then we save the code in ”Car.py”:
1 # Defining the Class Car color ) :
2 class Car :
3
def i n i t ( self , model , s e l f . model
4
= model s e l f . color = color
5
6
def displayCar ( s e l f ) : print
7
8
( s e l f . model) print ( s
9
e l f . color )
Then we create a Python Script (testCar.py) where we are using the Class:
1 # Importing the Car Class
2
from Car import Car
3
4
5
# Lets start using the Class
6
car1 = Car(”Tesla” , ”Red”)
7
8 car1 . displayCar ()
9
10
11
car2 = Car(”Ford” , ”Green”)
12
13 print ( car2 . model) print ”Blue”)
14 ( car2 . color )
15
16
17
car3 = Car(”Volvo” ,
18
19
print ( car3 . model) print
20
( car3 . color ) car3 .
21
22
color=”Black” car3 .
23
displayCar ()
24
[language=Python]
[End of Example]
68
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!
Create a Python Class where you calculate the degrees in Fahrenheit based on
the temperature in Celsius and vice versa.
[End of Exercise]
69
Chapter 8
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.
70
First, we create a Python module with the following functions (fahrenheit.py):
1 def c2f (Tc) :
2
3 Tf = (Tc ∗ 9/5) + 32
4
return Tf
5
6 def
7
f2c (Tf) :
8
9
Tc = (Tf −
10 return Tc 32) ∗(5/9)
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
and degrees.
71
This gives:
(8.4)
and
(8.5)
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]
Chapter 9
• ”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
72
9.2 Write Data to a File
To create a New file in Python, use the open() method, with one of the following
parameters:
• ”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
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
[End of Example]
• ”r” - Read - Default value. Opens a file for reading, error if the file does not
exist
73
[End of Example]
[End of Example]
[End of Example]
74
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!
[End of Exercise]
You can use the Random Generator in Python. An example of how to use the
Random Generator is shown below:
1 import random
2 for x in range (10) : data = random . randint
3
(1 ,31)
4
print ( data )
Make sure to log both the time and the temperature value Create
You should also plot the data you read from the File.
[End of Exercise]
Chapter 10
75
Error Handling in Python
10.1 Introduction to Error Handling
So far error messages haven’t been discussed. You could say that we have 2 kinds
of errors: syntax errors and exceptions.
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 recent call last ) :
7 or:
1 >>> ’2 ’ + 2
2 Traceback (most recent call last ) :
3
4 File ”<ipython−input−3−d2b23a1db757>” , line 1 , in <module>
5 ’2 ’ + 2
6
7
TypeError : must be str , not int
76
10.2 Exceptions Handling
It is possible to write programs that handle selected exceptions.
• The try block lets you test a block of code for errors.
• The finally block lets you execute code, regardless of the result of the
tryand except blocks.
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) except :
3
print (”The calculation failed ”)
4
or
1 try :
2 print (x)
3
except :
4
print (”x is not defined”)
The finally block, if specified, will be executed regardless if the try block raises an
error or not.
Example:
1 x=2
2
3 try :
4
print (x)
5
except NameError :
print (”x is not defined”)
except : print (”Something is wrong”) 77
finally :
print (”The Program is finished ”)
6
7
8
9
10
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(”myfile . txt”) f . write
3
(”Lorum Ipsum”)
4
except : print (”Something went wrong when
5
6
finally :
7 f . close () writing to the f i l e ”)
78
Chapter 11
Debugging in Python
Debugging is the process of finding and resolving defects or problems within a
computer program that prevent correct operation of computer software or a
system [14].
Debuggers are software tools which enable the programmer to monitor the
execution 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
debugging.
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 Editor.
Debugging is typically integrated with the Python Editor you are using.
Chapter 12
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 Packages as
mentioned previously.
79
12.1 What is PIP?
PIP is a package manager for Python packages, or modules if you like. PIP is a
tool for installing Python packages.
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 window
(macOS).
Some Python Editors also have a graphical way of installing Python Packages, like,
e.g., Visual Studio.
Part III
80
Chapter 13
Introduction to Python
Environments and Distributions
Python comes with many flavours and version.
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.
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/
81
13.1 Package and Environment Managers
The two most popular tools for installing Python Packages and setting up Python
environments are:
13.1.1 PIP
Web:
https://pypi.org
PIP is typically used from the Command Prompt (Windows) or Terminal window
(macOS).
13.1.2 Conda
Conda is an open source package management system and environment
management system that runs on Windows, macOS and Linux. Conda installs,
runs and updates packages and their dependencies.
Conda was created for Python programs, but it can package and distribute
software for any language.
Web:
https://conda.io/
Web:
https://www.anaconda.com
82
13.2 Python Virtual Environments
Python ”Virtual Environments” allow Python packages to be installed in an
isolated location for a particular application, rather than being installed globally.
Python Virtual Environments have their own installation directories and they
don’t share libraries with other virtual environments.
83
Chapter 14
Anaconda
Anaconda is not an Editor, but a Python Distribution package. Spyder is included
in the Python Distribution package. You can also use Anaconda to install other
Editors or Python packages.
Web:
https://www.anaconda.com
Wikipedia:
https://en.wikipedia.org/wiki/Anaconda(Pythondistribution)
84
Figure 14.1: Anaconda Navigator
Chapter 15
Enthought Canopy
Enthought Canopy is a Python Platform or Python Distribution for Scientists and
Engineers.
Canopy is freely available to all users under the Canopy license. Canopy provides
access to several hundreds Python packages, including NumPy, SciPy, Pandas,
Matplotlib, and IPython.
Web:
https://www.enthought.com/product/canopy/
Part IV
85
Python
Editors
86
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 advanced
programs a better editor is recommended.
• Spyder
• Visual Studio
• PyCharm
• Wing
• JupyterNotebook
I guess hundreds of different editors can be used for Python Programming, either
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.
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.
87
If you want to create Web Applications or other kinds of Applications, other
Editors are probably better to use.
88
Chapter 17
Spyder
Spyder - short for ”Scientific PYthon Development EnviRonment”.
• Variable Explorer
• etc.
Web: https://www.spyder-
ide.org
89
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
90
Chapter 18
Web:
https://code.visualstudio.com
Wikipedia:
https://en.wikipedia.org/wiki/VisualStudioCode
91
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
92
Chapter 19
Visual Studio
19.1 Introduction to Visual Studio
Microsoft Visual Studio is an integrated development environment (IDE) from
Microsoft. It is used to develop computer programs, as well as websites, web
apps, web services and mobile apps. The default (main) programming language
in Visual studio is C, but many other programming languages are supported.
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
isualStudio
93
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 manually 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).
94
Figure 19.2: Installing Python Extension for Visual Studio
2 >>> b = 5 >>> x = 3
3 >>> y = a∗x + b
4
>>> y
5
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.
95
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.
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]
96
Figure 19.5: New Python Project
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 different
Python Environments. See Figure 19.9.
97
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]
98
Figure 19.8: Install Python Packages from Visual Studio
Figure 19.9: Installing Python Packages for different Python Environments from
Visual Studio
99
Figure 19.10: Python Plotting Example with Visual Studio
Chapter 20
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.
100
Figure 20.1: PyCharm Python Editor
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
PyCharm for Anaconda. You can download it here:
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
language.
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.
101
Chapter 21
• Wing Personal – free version that omits some features, for students and
hobbyists
Web:
https://wingware.com
Wikipedia:
https://en.wikipedia.org/wiki/WingIDE
102
Chapter 22
Jupyter Notebook
The Jupyter Notebook is an open-source web application that allows you to
create and share documents that contain live code, equations, visualizations and
text.
Web:
http://jupyter.org
Wikipedia:
https://en.wikipedia.org/wiki/ProjectJupyter
22.1 JupyterHub
JupyterHub is a multi-user version of the notebook designed for companies,
classrooms and research labs [17].
103
JupyterHub is open-source and designed to be run on a variety of infrastructure.
This includes commercial cloud providers, virtual machines, or even your own
laptop hardware.
Web:
http://jupyter.org/hub
The good thing about Microsoft Azure Notebooks is that you have the
infrastructure 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]
104
Figure 22.3: Azure Notebook Project Notebooks
Part V
105
Chapter 23
Mathematics in Python
Python is a powerful tool for mathematical calculations.
If you are looking for similar using MATLAB, please take a look at these
resources: https://www.halvorsen.blog/documents/programming/matlab/
In this chapter we will focus on the math module that is part of the Python
Standard Library.
The math module has all the basic math functions you need, such as:
Trigonometric functions: sin(x), cos(x), etc. Logarithmic functions: log(), log10(),
etc. Constants like pi, e, inf, nan, etc. etc.
106
from math import ∗
x =
3.14y = sin (x)
print (y)
y = cos
(x)print (y)
If we need many functions we can do like this:
1
2
3
4
5
6
7
8
import math
import math as mt
print (y)
[End of Example]
107
There are advantages and disadvantages with the different approaches. In your
program you may need to use functions from many different modules or
packages. 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/
23.1.1 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]
(23.2)
Tip! You should split the expressions into different parts, such as:
poly = ax2 + bx + c
108
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)
[End of Exercise]
c2 = a2 + b2 (23.3)
[End of Exercise]
109
Exercise 23.1.4. Albert Einstein
Given the famous equation from Albert Einstein:
E = mc2 (23.4)
Calculate how much of the mass on the sun is used to create this energy per day.
How many years will it take to convert all the mass of the sun completely? Do we
need to worry if the sun will be used up in our generation or the next? justify the
answer.
[End of Exercise]
[End of Exercise]
110
23.2 Statistics
23.2.1 Introduction to Statistics
Mean or average:
The mean is the sum of the data divided by the number of data points. It is
commonly called “the average”, Formula for mean:
(23.5)
(23.6)
[End of Example]
Variance:
(23.7)
Standard deviation:
The standard deviation is a measure of the spread of the values in a dataset or
the value of a random variable. It is defined as the square root of the variance.
(23.8)
111
23.2.2 Statistics functions in Python
Mathematical statistics functions in Python:
https://docs.python.org/3/library/statistics.html statistics
is part of the The Python Standard Library.
For more information about the functions in the Python Standard Library, see:
https://docs.python.org/3/library/
[End of Example]
IMPORTANT: Do not name your file ”statistics.py” since the import will be
confused and throw the errors of the library not existing and the mean function
not existing.
You can also use the NumPy Library. NumPy is the fundamental package for
scientific computing with Python.
112
Below you find some examples how to use some of the statistics functions in
NumPy:
[End of Example]
Using the built-in functions in the Python Standard Library or the NumPy library
is straightforward.
Create your own Statistics Module in Python (e.g., ”mystatistics.py) and then
create a Python Script (e.g., ”testmystatistics.py) where you test these functions.
You should at least implement functions for mean, variance, standard deviation,
minimum and maximum.
[End of Exercise]
113
Note! Most of the trigonometric functions require that the angle is expressed in
radians.
Here we have used the Math module in the Python Standard Library.
For more information about the functions in the Python Standard Library, see:
https://docs.python.org/3/library/index.html
[End of Example]
In the example we have plotted sin(x), we can easily extend the program to plot
cos(x), etc.
114
For more information about the functions in the Python Standard Library, see:
https://docs.python.org/3/library/index.html
[End of Example]
The problem with using the Trigonometric functions in the the Math module
from the Python Standard Library is that they don’t handle an array as input.
We will use the NumPy library instead because they handle arrays, in addition to
all the handy functionality in the NumPy library.
1 import numpy as np
2 import matplotlib . pyplot as plt
3
4
xstart = 0
5
xstop = 2∗np. pi increment = 0.1 x = np. arange
6
( xstart , xstop , increment ) y = np. sin (x)
7
8
9
10
11 plt . plot (x , y) plt . t i t l e (
12 ’y=sin (x) ’ ) plt . xlabel ( ’x ’ )
13
plt . ylabel ( ’y ’ ) plt . grid ()
14
plt . axis ([0 , 2∗np. pi ,
15
16 −1, 1])
17 plt . show()
18
19 y = np. cos (x)
20 plt . plot (x , y) plt . t i t l e (
21
’y=cos (x) ’ ) plt . xlabel ( ’x ’ )
22
plt . ylabel ( ’y ’ ) plt . grid ()
23
plt . axis ([0 , 2∗np. pi ,
24
25 −1, 1])
26 plt . show()
27
28 y = np. tan(x)
29
plt . plot (x , y) plt . t i t l e (
30
’y=tan(x) ’ ) plt . xlabel ( ’x ’ )
31
plt . ylabel ( ’y ’ ) plt . grid ()
32
33
plt . axis ([0 , 2∗np. pi , plt .
34
show()
35 −1, 1])
[End of Example]
115
Exercise 23.3.1. Create Python functions for converting between radians an
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:
2π[radians] = 360[degrees] (23.9
This gives: )
(23.10)
and
(23.11)
Create two functions that convert from radians to degrees (r2d(x)) and from
degrees to radians (d2r(x)) respectively.
[End of Exercise]
Create a function that finds the angle A (in degrees) based on input arguments
(a,c), (b,c) and (a,b) respectively.
Use, e.g., a third input “type” to define the different types above.
Use you previous function r2d() to make sure the output of your function is in
degrees and not in radians.
116
(23.12)
(23.13) (23.14)
c2 = a2 + b2 (23.15)
1
117
126
Figure 23.3: Trigonometric Functions
Part VI Resources
119
Chapter 24
Python Resources
Here you find my Web page with Python resources [1]:
https://www.halvorsen.blog/documents/programming/python/
SciPy Library:
https://www.scipy.org
Visual Studio:
https://visualstudio.microsoft.com
PyCharm: https://www.jetbrains.com/pycharm/
Wing:
https://wingware.com
120
24.4 Python Tutorials
Python Tutorial - w3schools.com [13]:
https://www.w3schools.com/python/
Bibliography
[1] H.-P. Halvorsen, “Technology blog - https://www.halvorsen.blog,” 2018.
121
[14] Wikipedia, “Debugging - https://en.wikipedia.org/wiki/Debugging,” 2018.
122
Part VII Solutions
to Exercises
123
Start using Python
Simulation and Plotting of Dynamic System
Given the autonomous system:
x˙ = ax (1)
Where:
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 import math as mt import numpy
2 as np
3
import matplotlib . pyplot as plt
4
5
6
# Model Parameters
7
8
T=5
9
a = −1/T
10
11 # Simulation Parameters x0 = 1 t
12 =0
13
tstop
tstart==25
0 increment = 1
14
15
x=[]
16
17
x = np. zeros ( tstop+1) t = np. arange ( tstart ,
18
19
tstop+1,increment )
20
21
22 # Define the Function for k in
23 range ( tstop ) :
24 x [ k ] = mt. exp(a∗t [ k ]) ∗ x0
25
26
27 # Plot the Simulation Results plt . plot (t , x)
28
plt . t i t l e ( ’ Simulation of Dynamic System ’ ) plt .
29
xlabel ( ’ t ’ ) plt . ylabel ( ’x ’ ) plt . grid ()
30
plt . axis ([0 , 25 , 0 , 1])
plt . show() 124
31
32
33
34
35
36
37
[End of Exercise]
Python Programming
c Hans-Petter Halvorsen
ISBN:978-82-691106-4-7
125
126
Python Programming