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
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? 17
2.1 Introduction to Python . . . . . . . . . . . . . . . . . . . . . . . 17
2.1.1 Interpreted vs. Compiled . . . . . . . . . . . . . . . . . . 18
2.2 Python Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.2.1 Python Packages for Science and Numerical Computations 20
2.3 Anaconda . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
2.4 Python Editors . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
2.4.1 Python IDLE . . . . . . . . . . . . . . . . . . . . . . . . . 21
2.4.2 Visual Studio Code . . . . . . . . . . . . . . . . . . . . . . 22
2.4.3 Spyder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
2.4.4 Visual Studio . . . . . . . . . . . . . . . . . . . . . . . . . 22
2.4.5 PyCharm . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
2.4.6 Wing Python IDE . . . . . . . . . . . . . . . . . . . . . . 23
2.4.7 Jupyter Notebook . . . . . . . . . . . . . . . . . . . . . . 23
2.5 Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
2.6 Installing Python . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
2.6.1 Python Windows 10 Store App . . . . . . . . . . . . . . . 24
2.6.2 Installing Anaconda . . . . . . . . . . . . . . . . . . . . . 24
2.6.3 Installing Visual Studio Code . . . . . . . . . . . . . . . . 24
6
3.5.4 Run Python Scripts from Spyder . . . . . . . . . . . . . . 33
II Python Programming 50
5 Python Programming 51
5.1 If ... Else . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
5.2 Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
5.3 For Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
5.3.1 Nested For Loops . . . . . . . . . . . . . . . . . . . . . . . 57
5.4 While Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
5.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
7
10 Error Handling in Python 79
10.1 Introduction to Error Handling . . . . . . . . . . . . . . . . . . . 79
10.1.1 Syntax Errors . . . . . . . . . . . . . . . . . . . . . . . . . 79
10.1.2 Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . 79
10.2 Exceptions Handling . . . . . . . . . . . . . . . . . . . . . . . . . 80
11 Debugging in Python 82
14 Anaconda 88
14.1 Anaconda Navigator . . . . . . . . . . . . . . . . . . . . . . . . . 88
15 Enthought Canopy 90
IV Python Editors 91
16 Python Editors 92
17 Spyder 94
19 Visual Studio 98
19.1 Introduction to Visual Studio . . . . . . . . . . . . . . . . . . . . 98
19.2 Work with Python in Visual Studio . . . . . . . . . . . . . . . . . 98
19.2.1 Make Visual Studio ready for Python Programming . . . 99
19.2.2 Python Interactive . . . . . . . . . . . . . . . . . . . . . . 99
19.2.3 New Python Project . . . . . . . . . . . . . . . . . . . . . 100
20 PyCharm 106
8
V Python for Mathematics Applications 113
23 Mathematics in Python 114
23.1 Basic Math Functions . . . . . . . . . . . . . . . . . . . . . . . . 114
23.1.1 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
23.2 Statistics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
23.2.1 Introduction to Statistics . . . . . . . . . . . . . . . . . . 118
23.2.2 Statistics functions in Python . . . . . . . . . . . . . . . . 119
23.3 Trigonometric Functions . . . . . . . . . . . . . . . . . . . . . . . 121
23.4 Polynomials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
VI Resources 128
24 Python Resources 129
24.1 Python Distributions . . . . . . . . . . . . . . . . . . . . . . . . . 129
24.2 Python Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
24.3 Python Editors . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
24.4 Python Tutorials . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
24.5 Python in Visual Studio . . . . . . . . . . . . . . . . . . . . . . . 130
9
Part I
10
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.
11
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
12
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.
13
Figure 1.3: The Top Programming Languages - Stack Overflow Survey
14
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/
15
Figure 1.5: The Future of Python
16
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.
17
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.
18
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.
19
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.
20
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
21
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.
22
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/
23
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.
24
Download and install from:
https://code.visualstudio.com
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
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.
27
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 ” )
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 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.
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.
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 / 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 ?
32
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.
33
Figure 3.8: Running a Python Script
34
Figure 3.11: Running a Python Script in Spyder
35
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.
Python
36
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]
37
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
38
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 () )
39
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.
40
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. etc.
41
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
42
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
43
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
44
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.
45
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 ( )
46
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.
47
Figure 4.5: Plotting a Sine function in Python - Better Implementation
[End of Example]
48
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]
49
Part II
Python Programming
50
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 has
these features built-in, but the syntax is slightly different from one language to
another.
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
7 if b > a:
8 p r i n t ( ”b i s g r e a t e r than a ” )
9
10 i f a == b :
11 p r i n t ( ” a i s e q u a l t o b” )
Listing 5.1: Using Arrays in Python
51
Try to change the values for a and b.
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: Using Arrays in Python
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: Using Arrays in Python
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:
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 ] )
12
13
14 f o r x i n data :
15 print (x)
52
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.
53
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)
54
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.
55
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
56
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)
57
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!
58
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]
59
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
60
• 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 ) :
61
[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]
62
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:
63
[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.
64
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]
65