Python Programming Essentials
Python Programming Essentials
Programming
Hans-Petter Halvorsen
[Link]
Python Programming
Python Programming
Hans-Petter Halvorsen
2019
Python Programming
Qc Hans-Petter
Halvorsen August
82-691106-4-7
1
Preface
Python works on all the main platforms and operating systems used
today, such Windows, macOS, and Linux.
[Link]
2
LATEXis a document preparation system used for the communication
and publi- cation of scientific documents.
3
For more information about LATEX:
[Link]
Python Books
5
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.
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
6
7
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
8
dows..............................................................................................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
9
9.6 Exercises..................................................................................................76
11Debugging in Python 82
14Anaconda 88
14.1Anaconda Navigator............................................................................88
15Enthought Canopy 90
IV Python Editors 91
16Python Editors 92
17Spyder 94
19Visual Studio 98
19.1Introduction to Visual Studio..........................................................98
19.2Work 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
20PyCharm 106
10
22.2Microsoft Azure Notebooks...........................................................111
VI Resources 128
24Python Resources 129
24.1Python Distributions.........................................................................129
24.2Python Libraries................................................................................129
24.3Python Editors....................................................................................129
24.4Python Tutorials.................................................................................130
24.5Python in Visual Studio..................................................................130
11
Part I
12
Chapter 1
Introduction
With this textbook you will learn basic Python programming. The
textbook contains lots of examples and self-paced tasks that the
users should go through and solve in their own pace.
The Internet has also changed the way we use devices and
software. We still have traditional desktop applications, but Web
Sites, Web Applications and so- called Apps for Smartphones, etc.
are dominating the software market today.
14
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.
16
Figure 1.2: The Most Popular Programming Languages
• Mobile
• Enterprise
• Embedded
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.
• Python has a simple and flexible code structure and the code
is easy to read.
17
Figure 1.3: The Top Programming Languages - Stack Overflow Survey
1.2 MATLAB
If you are looking for MATLAB, please see the following:
[Link]
19
Figure 1.5: The Future of Python
20
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.
22
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.
23
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.
25
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.
26
Anaconda includes Python, the Jupyter Notebook, and other
commonly used packages for scientific computing and data science.
27
They offer a free version (Anaconda Distribution) and a paid
version (Enter- prise) Anaconda is available for Windows, macOS,
and Linux
Web:
[Link]
Wikipedia:
[Link]
on)
Spyder and the Python packages (NumPy, SciPy, Matplotlib, ...) mention above
+++ are included in the Anaconda Distribution.
29
2.4.2 Visual Studio Code
Visual Studio Code is a source code editor developed by Microsoft for
Windows, Linux and macOS.
Web:
[Link]
2.4.3 Spyder
Spyder is an open source cross-platform integrated development
environment (IDE) for scientific programming in the Python
language.
Web:
[Link]
Wikipedia:
[Link]
Web:
[Link]
Wikipedia:
[Link] 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.
30
Web:
[Link]
Web:
[Link]
Wikipedia:
[Link]
upyter
2.5 Resources
Here are some useful Python
32
[Link]
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 the basic Python examples in the beginning, the basic Python
software from:
[Link] 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).
Microsoft Store version of Python 3.7 is very basic but it’s good
enough to run the simple scripts.
34
Download and install from:
[Link]
35
Chapter 3
36
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]
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.
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
37
things out.
Below we see how we can run Python from the Console which is part of the OS.
38
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.
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:
>>> p r i n t (” H e l l o World ”)
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 [Link] 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 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 ”[Link]” is located. See
Click Save and open the Command Prompt once more and enter
”python” to verify it works. See Figure 3.3.
41
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.
42
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.
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
World 43
How are you?
2
3
44
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 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.
45
Figure 3.8: Running a Python Script
46
Figure 3.11: Running a Python Script in Spyder
47
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
48
come from constants, from computation involving values of other
variables, or from the output of a function.
Python
49
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]
50
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
51
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 + 2 j # complex
Listing 4.5: Numeric 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[
6
7 1])
8 print(a[2:5])
print(len(a))
52
9 p r i n t ( a . upper ( ) )
10 p r i n t ( a . r e p l a c e ( ”H”
11 , ”J” ) ) p r i n t ( 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]
The following example asks for the user’s name, then, by using the
input() method, the program prints the name to the screen:
1 p r i n t ( ” Enter your name : ” )
2 x = input ( )
3 p r i n t ( ” Hello , ” + x )
Listing 4.8: String Input
[End of Example]
In another chapter we will learn to create our own functions from scratch.
53
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.
print(y) 54
6
55
We can also write it like this:
1 import math as mt
2
3 x = 3 . 14
4 y = mt . s i n ( x )
5
6 print(y)
[End of Example]
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.
56
• Matplotlib - Matplotlib is a Python 2D plotting library
57
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.
y)
In this example we use both the math module in the Python
Standard Library and the NumPy library:
1 import math as mt
2 import numpy as
3
4 np x = 3
5
6 y = mt . s i n (
7
8 x)print(y)
9
10
11 y = np . s i n
12
13 (x)print(
58
6 y = sin(x)
7
8 print(y)
9
10
11 y = sin(
12
13 x)print
In
( y )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:
[Link]
on/
The main difference from MATLAB is that you need to import the
library, either the whole library or one or more functions.
59
For simplicity we import the whole library like this:
1 import m a tp l o tl i b . pyplot as plt
60
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.
61
Figure 4.3: Plotting in Python
[End of Example]
• plot()
• xlabel()
• ylabel()
• show()
1 import numpy as np
2 import m a tp l o t l i b . pyplot
3
4 as p l t x = [ 0 , 1 , 2 , 3 , 4 ,
5
6 5, 6, 7]
7
8 y = np . s i n ( x )
9
10 plt .plot(x, y)
11 [Link]( ’x’)
62
Figure 4.4: Plotting a Sine function in Python
[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.
[End of Example]
64
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!
plots.
You should use all the Plotting functions listed below in your code:
• plot()
• title()
• xlabel()
• ylabel()
• axis()
• grid()
• legend()
• show()
[End of Exercise]
65
Part II
Python Programming
66
Chapter 5
Python Programming
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 print(”a is g r e a t e r than b” )
6
7 if b > a:
8 p r i n t ( ”b is greater than a” )
9
10 if a == b :
11 print(”a is equal to b” )
Listing 5.1: Using Arrays in Python
67
Try to change the values for a and b.
Using If -
Else:
1 a = 5
2 b = 8
3
4 if a > b:
5 print(”a is greater
6 than b” ) e l s e :
7 p r i n t ( ”b i s g r e a t e r than a or a and b are equal ” )
Listing 5.2: Using Arrays in Python
Using
Elif :
1 a =
2 5
3 b =
4 if a > b:
5 print(”a greater than
6 iselif b > a: b” )
7 p r i n t ( ”b greater than
8 i s e l i f a == a” )
9 b:
print(”a Listing
equal to 5.3:
b” ) 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:
69
16
17
18 data . append ( 1 1 . 4 )
19
20
21 N = len(
22
23 data ) p r i n t
24
25 (N)
26
27
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 = c a r s [ 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.
70
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 i n 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.
Finally, you can also use the range() function like this:
1 start = 4
2 stop = 12 #but not inclu
3 d i n g s te p = 2
4
5 f o r x i n range ( s ta r t , stop ,
6 s te p ) : p r i n t ( x )
71
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.
1 data = [ 1 , 5, 6, 3, 12 , 3]
2
3 sum = 0
4
5 #Find the Sum o f all the numbers
6 f o r x i n data :
7 sum = sum + x
8
9 p r i n t ( sum)
10
11 #Find the Mean or Average of all the numbers
12
13 N = l e n ( data )
14
15 mean = sum/N
16
17 p r i n t ( mean )
[End of Example]
Some sources omit the initial 0, instead beginning the sequence with two 1s.
72
In mathematical terms, the sequence Fn of Fibonacci numbers is
defined by the recurrence relation
f0 = 0, f1 = 1
Alternative solution:
1 N = 10
2
3 fib = [0, 1]
4
5
6 f o r k i n range (N−2) :
7 fib next = 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
73
11 f o r k i n range (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 for i i n range ( 1 , 10 ) :
2 f o r k i n range ( 1 ,
3 10 ) : p r i n t ( i , k
)
The first 25 prime numbers (all the prime numbers less than 100) are:
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83,
89, 97
74
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 wh i l e m >
2
4 : print
5 m(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!
75
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]
76
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.
Function. Scripts:
tasks Functions:
78
• 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 def
2
FunctionName :
3 <statement −1>
4 .
5
.
6 <statement −N>
r e tu r n . . .
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 ) :
80
[End of Example]
[End of Example]
81
21 data = [ 1 , 5, 6, 3, 12 , 3]
22
23
24 totalsum , mean = s t a t (
25
26 data ) p r i n t ( totalsum ,
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]
π
r[radians] = d[degrees] × (
) (6.3)
180
Create two functions that convert from radians to degrees (r2d(x))
and from degrees to radians (d2r(x)) respectively.
82
Test the functions to make sure that they work as expected.
83
[End of Exercise]
Some sources omit the initial 0, instead beginning the sequence with two 1s.
f0 = 0, f1 = 1
[End of Exercise]
84
Tip! I guess this can be implemented in many different ways, but
one way is to use 2 nested For Loops.
85
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]
86
Chapter 7
7.1 Introduction
Python is an object oriented programming (OOP) language. Almost
everything in Python is an object, with its properties and methods.
1 c l a s s ClassName :
2 <statement −1>
3 .
4 .
5 .
6 <statement −N>
1 c l a s s Car :
2 model = ”
3 Volvo ” c o l o r
4 = ” Blue ”
5
6
7 car = Car ( )
8
9
10 p r i n t ( car .
Listing 7.1: Simple Python Class
88
This example don’t illustrate the good things with classes so we
will create some more examples.
[End of Example]
[End of Example]
89
12 car 2 = Car ( ” Volvo ” , ” Blue ” )
13
14 p r i n t ( car 2 .
15 model ) p r i n t (
car 2 . c o l o r )
Listing 7.3: Python Class Constructor Example
As you see from the code we have now defined a Class ”Car” that
has 2 Class variables called ”model” and ”color”, and in addition
we have defined a Func- tion (or Method) called ”displayCar()”.
Its normal to use the term ”Method” for Functions that are defined
within a Class.
You declare class methods like normal functions with the exception
that the first argument to each method is self.
To create instances of a class, you call the class using class name
and pass in whatever arguments its init () method accepts.
For example:
90
1 car 1 = Car ( ” Tesla ” , ”Red” )
[End of Example]
We start by creating the Class and then we save the code in ”[Link]”:
1 # De f i n i n g the Clas
s Car
3 c l a d
2 s se f Cari n: i t ( s e l f , model , c o l
or):
4 s e l f . model = model
5
6 [Link] = color
7 d e f di s play Car ( s
elf):
8 print(self .
model )
Listing 7.5: Define Python Class in separate File
Then we create a Python Script ([Link]) where we are using the Class:
1 # Importing the Car Clas s
2 from Car import Car
3
4 # Lets start us i n g the Clas s
5
6 car 1 = Car ( ” Tesla ” , ”Red” )
7
8 car 1 . di s play Car ( )
9
10
11 car 2 = Car ( ” Ford” , ” Green” )
12
13 p r i n t ( car 2 . model )
14 p r i n t ( car 2 . c o l o r )
15
16
17 car 3 = Car ( ” Volvo ” , ” Blue ” )
18
19 p r i n t ( car 3 . model )
20 p r i n t ( car 3 . c o l o r )
21
22 car 3 . c o l o r=” Black ”
23
24 car 3 . di s play Car ( )
Listing 7.6: Script that is using the Class
[language=Python]
[End of Example]
91
7.3 Exercises
Below you find different self-paced Exercises that you should go
through and solve on your own. The only way to learn Python is to
do lots of Exercises!
[End of Exercise]
92
Chapter 8
As your program gets longer, you may want to split it into several
files for easier maintenance. You may also want to use a handy
function that you have written in several programs without copying
its definition into each program.
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.
93
The formula for converting from Celsius to Fahrenheit is:
Tf = (Tc × 9/5) + 32 (8.1)
94
The formula for converting from Fahrenheit to Celsius is:
8.2 Exercises
Below you find different self-paced Exercises that you should go
through and solve on your own. The only way to learn Python is to
do lots of Exercises!
96
and degrees.
π
r[radians] = d[degrees] × ( ) (8.5)
180
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]
97
Chapter 9
9.1 Introduction
Python has several functions for creating, reading, updating, and
deleting files. The key function for working with files in Python is
the open() function.
opening a file:
• ”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
In addition you can specify if the file should be handled as binary or text mode
• ”x” - Create - Creates the specified file, returns an error if the file exists
• ”w” - Write - Opens a file for writing, creates the file if it does not exist
98
”a” - Append - Opens a file for appending, creates the file if it
• does not exist
99
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
[End of Example]
• ”r” - Read - Default value. Opens a file for reading, error if the
file does not exist
1 f = open ( ” m y f i l e . txt ” , ” r ” )
2
3 data = f . read
4
5 () print(
6
7 data )
Listing 9.2: Read Data from a File
[End of Example]
100
1 data = [ 1 . 6 , 3.4, 5.5, 9.4]
2
3 f = open ( ” m y f i l e . txt ”
4
5 , ”x” ) f o r value i n data
6
7 :
8 record = str(
9 value ) f . w r i te ( r
10 ecord)
f . w r i te ( ” \n” )Listing 9.3: Logging Data to File
[End of Example]
1 f = open ( ” m y f i l e . txt ” , ” r ” )
2
3 for record in f :
4 record = [Link](
5
” \n” , ”” ) p r i n t ( r e c o r d )
6
7
f. close()
[End of Example]
9.6 Exercises
Below you find different self-paced Exercises that you should go
through and solve on your own. The only way to learn Python is to
do lots of Exercises!
101
Log these data to a File.
102
[End of Exercise]
1 import random
2 f o r x i n range ( 10 ) :
3 data = random . r an d i n t (
4 1 , 3 1 ) p r i n t ( data )
Listing 9.5: Read Data from a File
that reads the same data. You should also plot the
[End of Exercise]
103
Table 9.1: Logged Data
Time Value
1 22
2 25
3 28
... ...
104
Chapter 10
10.1.2 Exceptions
Even if a statement or expression is syntactically correct, it may
cause an error when an attempt is made to execute it. Errors
detected during execution are called exceptions and are not
unconditionally fatal: you will soon learn how to handle them in
Python programs. Most exceptions are not handled by programs,
however, and result in error messages as shown here:
1 >>> 10 ∗ ( 1 / 0 )
2 Traceback ( most r e c e n t call last):
3
4 F i l e ”<ipython −input −2−0b 280 f 36835 c >” , l i n e 1 , i n
<module>
5 10 ∗ ( 1 / 0 )
6
or:
1 >>> ’ 2 ’ + 2
2 Traceback ( most r e c e n t call last):
3
105
4 F i l e ”<ipython −input −3−d2b23a1db757>” , line 1, in
5 <module>
6 ’2’ + 2
7
TypeError : must be s tr , not int
• 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 try- and except blocks.
1 tr y :
2 10 ∗ ( 1 / 0 )
3 except :
4 p r i n t ( ”The c a l c u l a t i o n failed”)
or:
1 tr y :
2 print(
3 x ) except :
4 p r i n t ( ”x is not defined”)
Example:
106
1 x=2
2
3 tr y :
4 print(x)
5 except NameError :
6 p r i n t ( ”x i s not d e f i n e d
7 ” ) except :
8 p r i n t ( ” Something i s
9 wrong” ) f i n a l l y :
10 p r i n t ( ”The Program i s f i n i s h e d ” )
In general you should use try - except - finally when you try to open
a File, read or write to Files, connect to a Database, etc.
Example:
1 tr y :
2 f = open ( ” m y f i l e .
3 txt ” ) f . w r i te (
4 ”Lorum Ipsum” )
5 except :
6 p r i n t ( ” Something went wrong when w r i t i n g to
7 the f i l e ” ) f i n a l l y :
f. close()
107
Chapter 11
Debugging in Python
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.
108
Chapter 12
A package contains all the files you need for a module. Modules
are Python code libraries you can include in your project.
If you do not have PIP installed, you can download and install it
from this page: [Link]
110
Chapter 13
Introduction to
Python
Environments and
Distributions
• Enthought Canopy
• WinPython
• etc.
Then install the additional Python Packages you need by using PIP.
[Link]
13.1.1 PIP
Web:
[Link]
13.1.2 Conda
Conda is an open source package management system and
environment man- agement system that runs on Windows, macOS
and Linux. Conda installs, runs and updates packages and their
dependencies.
Conda was created for Python programs, but it can package and
distribute soft- ware for any language.
Distribution. Web:
[Link]
113
Chapter 14
Anaconda
Linux. Web:
[Link]
Wikipedia:
[Link]
on)
114
Figure 14.1: Anaconda Navigator
115
Chapter 15
Enthought Canopy
Web:
[Link]
opy/
116
Part IV
Python Editors
117
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.
For simple Python programs you can use the IDLE Editor, but for
more ad- vanced programs a better editor is recommended.
• Spyder
• Visual Studio
• PyCharm
• Wing
• JupyterNotebook
119
Chapter 17
Spyder
120
• Variable Explorer
• etc
.
Web:
[Link]
Web:
[Link]
om
121
Chapter 18
Terminal”
Web:
[Link]
122
Wikipedia:
[Link]
123
18.2 Python in Visual Studio Code
In addition to Visual Studio Code you need to install the Python
extension for Visual Studio Code.
[Link]
Web:
[Link]
hon
124
Chapter 19
Visual Studio
macOS.
Web:
[Link]
Wikipedia:
[Link] isualStudio
125
Figure 19.1: Using Visual Studio as Python Editor
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).
127
Figure 19.2: Installing Python Extension for Visual Studio
2 >>> b = 5
3 >>> x = 3
4 >>> y = a ∗ x + b
5 >>> y
Start by select from the menu: File - New - Project... The New
Project window pops up. See Figure 19.5.
We can create an ordinary Python Application (one or more Python
Scripts), we can choose to create a Web Application using either
Web Frameworks like Django or Flask, or we can create different
Desktop GUI applications. We can also create Games.
128
Figure 19.4: Python Interactive
1 p r i n t ( ” H e l l o World” )
Hit F5 (our click the green arrow) in order to run or execute the
Python program. You can also right click on the file and select ”Start
without Debugging”.
[End of Example]
130
Figure 19.5: New Python Project
14 [Link]( ’x’)
15 [Link](
16 ’y’)plt .gri
17 d()
18 p l t . a x i s ( [ 0 , 2∗ np . pi , −1, 1])
You can also easily see which Python Packages that are installed
for the differ- ent Python Environments. See Figure 19.9.
131
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]
132
Figure 19.7: Select your Python Environment
133
Figure 19.9: Installing Python Packages for different Python
Environments from Visual Studio
134
Chapter 20
PyCharm
Web:
[Link]
Wikipedia:
[Link]
m
135
[Link]
We have code editors like Visual Studio and Visual Studio Code
which can be used for many different programming languages by
installing different types of plugins.
Editors like Spyder and PyCharm are tailor-made editors for the
Python lan- guage.
136
Chapter 21
Web:
[Link]
137
Wikipedia:
[Link]
E
138
Chapter 22
Jupyter Notebook
Web:
[Link]
Wikipedia:
[Link]
upyter
139
22.1 JupyterHub
JupyterHub is a multi-user version of the notebook designed for
companies, classrooms and research labs [17].
Web:
[Link]
The good thing about Microsoft Azure Notebooks is that you have
the infras- tructure and everything up and running ready for you to
use. You can use it for free as well.
Web:
[Link]
[End of Example]
140
Figure 22.3: Azure Notebook Project Notebooks
141
Part V
142
Chapter 23
Mathematics in Python
If you are looking for similar using MATLAB, please take a look at
these re- sources:
[Link]
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: Trigono- metric functions: sin(x), cos(x), etc. Logarithmic
functions: log(), log10(), etc. Constants like pi, e, inf, nan, etc. etc.
[End of Example]
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.
[End of Exercise]
Given a = 1, b = 3, c = 5 Find f
(9) (The answer should be f (9)
= 0.0044)
Tip! You should split the expressions into different parts, such as:
poly = ax2 + bx + c
num = . . .
den = . . .
f =...
This makes the expression simpler to read and understand, and you
minimize the risk of making an error while typing the expression in
Python.
When you got the correct answer try to change to, e.g., a = 2, b
= 8, c = 6 Find f (9)
[End of Exercise]
c2 = a2 + b2 (23.3)
1 d e f pythagoras ( a , b )
2 ...
3 ...
4 r e tu r n c
[End of Exercise]
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]
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:
N
x1 + x2 + x3 + 1
x¯ = xN =L xi (23.5)
... + N
N i=1
148
[End of Example]
Variance:
N
1
var(x) = L − x¯2) (23.7)
(xi
Standard N
i=1
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.
v
√ u 1 L
N
Below you find some examples how to use some of the statistics
functions in the statistics module in Python Standard Library:
149
1 import statistics as s t
2
150
11 print(st dev)
12
13 # Median
14 med = s t . median ( data )
15 p r i n t ( med)
16
17 # Variance
18 var = s t . va r i a n c e ( data )
19 p r i n t ( var )
Listing 23.1: Statistics functions in Python
[End of Example]
You can also use the NumPy Library. NumPy is the fundamental
package for scientific computing with Python.
Below you find some examples how to use some of the statistics
functions in NumPy:
1 import numpy as np
2
151
[End of Example]
[End of Exercise]
1 import math as mt
2
3 x = 2∗mt . p i
4
5
y = mt . s i n (
6
x)print(y)
7
8
y = mt . cos (
9
x)print(y
10
)
11
12
y = mt . tan (
x)print(y
Listing 23.3: Trigonometric Functions in Math module
Here we have used the Math module in the Python Standard Library.
152
[End of Example]
1 import math as mt
2 import m a tp l o t l i b . pyplot as plt
3
4 xdata = [
5 ] ydata =
6 []
7
8 f o r x i n range ( 0 , 10
9 ) : xdata . append ( x )
10 y = mt . s i n ( x
11 ) ydata . append
12 (y)
13
[End of Example]
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 m a tp l o t l i b . pyplot as plt
3
4 xstart = 0
5 xstop = 2∗ np .
6
p i incre me nt
= 0.1
7
8
9
x = np . arange ( xs ta r t , xstop ,
10
i ncre me nt ) y = np . s i n ( x )
153
11 plt .plot(x, y)
12 p l t . t i t l e ( ’ y=s i n ( x ) ’ )
13 [Link]( ’x’)
14 [Link](
15 ’y’)plt .gri
16 d()
17 p l t . a x i s ( [ 0 , 2∗ np . pi , −1, 1])
18 p l t . show ( )
19
20 y = np . cos (
21 x)[Link](
22 x, y)
23 p l t . t i t l e ( ’ y=cos ( x ) ’ )
24 [Link]( ’x’)
25 [Link](
26 ’y’)plt .gri
27 d()
28
p l t . a x i s ( [ 0 , 2∗ np . pi , −1, 1])
29 p l t . show ( )
30
31 y = np . tan (
32
x) [Link]
33
(x, y)
34
p l t . t i t l e ( ’ y=tan ( x ) ’ )
35
[Link]( ’x’)
Listing 23.5: Trigonometric Functions using NumPy
[End of Example]
π
r[radians] = d[degrees] × (
) (23.11)
180
Create two functions that convert from radians to degrees (r2d(x))
and from degrees to radians (d2r(x)) respectively.
154
These functions should be saved in one Python file .py.
[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.
a a
sin(A) = → A = arcsin( ) (23.12)
c c
b b
cos(A) = → A = arccos( ) (23.13)
c c
a a
tan(A) = → A = arctan( ) (23.14)
b b
c2 = a2 + b2 (23.15)
1 >>> a=5
2 >>> b=8
3 >>> c = s q r t ( a ∗∗2 + b ∗∗ 2 )
4
5 >>> A = r i g h t t r i a n g l e ( a , c , ’ s i n ’ )
6 A =
7 32 . 0054
8
9 >>> A = r i g h t t r i a n g l e ( b , c , ’ cos ’ )
10 A =
11 32 . 0054
12 >>> A = r i g h t t r i a n g l e ( a , b , ’ tan ’ )
13 A =
14 32 . 0054
We also see that the answer in this case is the same, which is expected.
155
[End of Exercise]
[End of Exercise]
Plot sin(θ) and cos(θ) for≤0 θ ≤ 2π in the same plot (both in the
same plot and in 2 different subplots).
Make sure to add labels and a legend and use different line styles
and colors for the plots.
[End of Exercise]
23.4 Polynomials
A polynomial is expressed as:
(23.17) where p1, p2, p3, ... are the coefficients of the polynomial.
Web:
[Link]
127
Part VI
Resources
128
Chapter 24
Python Resources
SciPy Library:
[Link]
Matplotlib Library:
[Link]
129
24.3 Python Editors
Spyder:
[Link]
[Link]
130
Visual studio Code:
[Link]
Visual Studio:
[Link]
PyCharm:
[Link]
Wing:
[Link]
Jupyter Notebook:
[Link]
131
Bibliography
133
[18] [Link], “The python
standard library -
[Link] 2018.
134
Part VII
Solutions to Exercises
135
Start using Python
Create a Script in Python (.py file) where you plot the solution x(t) in
the time interval:
0 ≤ t ≤ 25
Add Grid, and proper Title and Axis Labels to the plot.
Python Script:
1 import math as mt
2 import numpy as np
3 import m a tp l o t l i b . pyplot as plt
4
5
6 # Model Parameters
7 T = 5
8 a = −1/T
9
10 # S i m u l a t i o n Parameters
11 x0 = 1
12 t = 0
13
14 tstart = 0
136
15 ts to p = 25
16
17 i ncrement = 1
18
19 x = []
20 x = np . z e r o s ( ts to p +1)
21
22 t = np . arange ( t s t a r t , ts to p +1, i ncre me nt )
23
24
25 # Define the Function
26 f o r k i n range ( ts to p ) :
27 x [ k ] = mt . exp ( a ∗ t [ k ] ) ∗ x0
28
29
30 # Plot the S i m u l a t i o n Re s u l ts
31 plt .plot(t,x)
32 p l t . t i t l e ( ’ S i m u l a t i o n o f Dynamic System ’ )
33 plt . xlabel( ’t ’)
34 plt . ylabel( ’x’)
35 [Link]()
36 p l t . a x i s ( [ 0 , 25 , 0 , 1 ] )
37 p l t . show ( )
[End of Exercise]
137
Python Programming
Qc Hans-Petter
Halvorsen August
82-691106-4-7
138
Python Programming
Python IDLE is suitable for basic Python programming due to its simplicity and integration with Python's interpreter, but it lacks advanced features such as extensive debugging tools, version control integration, and plugins offered by more sophisticated IDEs like PyCharm or Visual Studio Code. Advanced programming often requires features like better user interface design, code completion, and debugging tools, which are more robustly provided in other editors such as Spyder or Visual Studio Code .
Visual Studio Code supports Python through extensions that enable syntax highlighting, IntelliSense, and debugging features. It requires an additional installation of a Python interpreter but offers flexibility with various language support and extensions. PyCharm, however, is specifically designed for Python development, providing a more integrated experience with built-in tools for testing, deployment, and database management. While both offer robust environments, PyCharm's focus on Python might offer a more streamlined experience for Python developers, whereas Visual Studio Code might appeal to those who work with multiple languages .
Python's manageability of scientific libraries such as NumPy, SciPy, and Matplotlib greatly enhances scientific research by offering a highly integrated and extensible platform for complex computations. NumPy and SciPy provide powerful tools for numerical data processing and analysis, ensuring precision with optimized algorithms for computations. Matplotlib allows for detailed and accurate visual representation of data. The synergy between these packages ensures that researchers can model, analyze, and visualize data within a coherent workflow, enhancing computation accuracy and the ability to handle large datasets efficiently, which is critical in scientific endeavors .
The Math module provides basic trigonometric functions such as sin, cos, and tan, which are suitable for handling individual number operations and are part of the Python Standard Library. However, it does not support array operations directly. In contrast, NumPy functions are optimized for array operations, allowing vectorized computations for trigonometric functions, which makes it far more efficient for large-scale numerical computations involving arrays. The choice between the two depends on the specific needs for either single value computations or array processing .
Anaconda's inclusion of Jupyter Notebook significantly impacts data science practices by providing a flexible and powerful tool for interactive computing. Jupyter allows users to create and share documents that integrate live code, equations, visualizations, and narrative text, which facilitates exploratory data analysis and supports reproducibility. The immediacy and clarity offered by Jupyter for testing hypotheses and displaying results enhance communication among data scientists and stakeholders. Furthermore, its integration with Anaconda simplifies installation and dependency management, promoting widespread adoption in data science workflows .
Downloading Python from the official website provides users with the core interpreter and a basic code editor, suitable for beginners to learn the basics. The Windows 10 Store App offers a straightforward installation for quick-start users, requiring less configuration. However, using Anaconda provides an enhanced user experience by pre-packaging a collection of essential scientific libraries and tools like Jupyter Notebook, ideal for users expecting to engage in data analysis or scientific computing without managing dependencies manually. Thus, Anaconda is often preferred for its comprehensive environment, while the website and Store App serve simpler or more basic needs .
When choosing between editors like Spyder and Visual Studio for scientific computing, a programmer should consider the project's complexity, their familiarity with the editor, integrated tools, and specific needs such as debugging capabilities. Spyder is especially beneficial for numeric and scientific tasks due to its MATLAB-like interface and integration with Anaconda, making it suitable for users who focus on scientific computations. Visual Studio offers wider language support and might be more suitable for developers who also need robust tools for other languages and platforms, especially where features like Git integration or comprehensive project management tools are essential .
NumPy is the fundamental package for scientific computing with Python, primarily focusing on array manipulation, basic computations, and linear algebra. It provides a powerful N-dimensional array object. On the other hand, SciPy is built on top of NumPy and extends it with additional modules for optimization, integration, and interpolation, making it more suitable for complex scientific calculations .
Anaconda simplifies Python programming by providing a comprehensive distribution that includes the Python compiler, packages, and the Spyder editor, all in one package. This contrasts with manually installing packages, which can be cumbersome and prone to dependency conflicts. Anaconda includes popular libraries such as NumPy, SciPy, and Matplotlib out of the box, offering the same features as MATLAB, thus streamlining the setup process for scientific computing .
Spyder resembles MATLAB in its focus on scientific and numerical computations and its integrated development environment structure, which includes a code editor, iPython console window, and variable explorer. However, unlike MATLAB, Spyder is open-source and part of the Anaconda distribution, which integrates Python for more extensive general programming capabilities. Spyder is also easily installable via Anaconda and is considered a good choice for users familiar with MATLAB .