Python Programming
Python Programming
2: วแปร (Variables)
ส ป ณสม ห กเ าใจ ายๆ ของ วแปรในภาษา Python :
การส าง วแปร: เราจะใ เค องหมายเ า บ (=) ในการ หนด าใ วแปร
ช ด อ ลแบบ ดห น (Dynamic Typing): ใน Python เราไ องบอก วง
ห า า วแปร เ น อ ลประเภทไหน (เ น วเลขห อ อความ) และเรา ง
สามารถเป ยนประเภท อ ลของ วแปร นไปมาไ ตลอดเวลาในขณะ โปรแกรม
Chapter
งาน
4
แห ง มาของ าใน วแปร: วแปรสามารถ บ อ ลมาจาก 3 แห งห กๆ อ:
Basic Python Programming
าตรงๆ (Constants): ใ าลงไป อๆ เลย เ น วเลขห อ อความ
ผลจากการ นวณ (Computations): เ ดจากการเอา วแปร นมาบวก ลบ
ณ หาร น
4.1ผล พ จาก Python
Basic ง น (Function
Program Output): า ไ ก บ นมาจาก ง น างๆ
เราเ ยกใ
We will start using Python and create some code examples.
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 o↵ 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
Hnhfmnt,.gf
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 di↵erent 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 di↵erent approaches. In your
program you may need to use functions from many di↵erent 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 di↵erent
libraries have some functions with the same name but di↵erent 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:
[Link]
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
di↵erent 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 di↵erent functions with the same
name that have di↵erent meaning in 2 di↵erent libraries.
[End of Example]
Anaconda:
[Link]
If you are familiar with MATLAB and basic plotting in MATLAB, using the
Matplotlib is very similar.
The main di↵erence 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 di↵erent libraries have
some functions with the same name but di↵erent 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 di↵erent 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
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 di↵erent 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 di↵erent 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 f or 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
fn = fn 1 + fn 2 (5.1)
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 di↵erent 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 di↵erent 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 di↵erent
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., [Link]) 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 di↵erent 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.
fn = fn 1 + fn 2 (6.4)
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 di↵erent 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
Chapter 7
7.1 Introduction
Python is an object oriented programming (OOP) language. Almost everything
in Python is an object, with its properties and methods.
The foundation for all object oriented programming (OOP) languages are Classes.
1 c l a s s ClassName :
2 <s t a t e m e n t 1>
3 .
4 .
5 .
6 <s t a t e m e n t N>
1 c l a s s Car :
2 model = ” Volvo ”
3 c o l o r = ” Blue ”
4
5
6 c a r = Car ( )
7
8
9 p r i n t ( c a r . model )
10 print ( car . color )
Listing 7.1: Simple Python Class
66
This example don’t illustrate the good things with classes so we will create some
more examples.
[End of Example]
[End of Example]
67
12 c a r 2 = Car ( ” Volvo ” , ” Blue ” )
13
14 p r i n t ( c a r 2 . model )
15 print ( car2 . c o l o r )
Listing 7.3: Python Class Constructor Example
As you see from the code we have now defined a Class ”Car” that has 2 Class
variables called ”model” and ”color”, and in addition we have defined a Func-
tion (or Method) called ”displayCar()”.
Its normal to use the term ”Method” for Functions that are defined within a
Class.
You declare class methods like normal functions with the exception that the
first argument to each method is self.
To create instances of a class, you call the class using class name and pass in
whatever arguments its init () method accepts.
For example:
68
1 c a r 1 = Car ( ” T e s l a ” , ”Red” )
[End of Example]
Then we create a Python Script ([Link]) where we are using the Class:
1 # I m p o r t i n g t h e Car C l a s s
2 from Car im por t Car
3
4 # Lets s t a r t using the Class
5
6 c a r 1 = Car ( ” T e s l a ” , ”Red” )
7
8 car1 . displayCar ()
9
10
11 c a r 2 = Car ( ” Ford ” , ” Green ” )
12
13 p r i n t ( c a r 2 . model )
14 print ( car2 . c o l o r )
15
16
17 c a r 3 = Car ( ” Volvo ” , ” Blue ” )
18
19 p r i n t ( c a r 3 . model )
20 print ( car3 . c o l o r )
21
22 c a r 3 . c o l o r=” Black ”
23
24 car3 . displayCar ()
Listing 7.6: Script that is using the Class
[language=Python]
[End of Example]
69
7.3 Exercises
Below you find di↵erent 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]
70
Chapter 8
As your program gets longer, you may want to split it into several files for easier
maintenance. You may also want to use a handy function that you have written
in several programs without copying its definition into each program.
To support this, Python has a way to put definitions in a file and use them
in a script or in an interactive instance of the interpreter (the Python Console
window).
Python allows you to split your program into modules that can be reused in
other Python programs. It comes with a large collection of standard modules
that you can use as the basis of your programs as we have seen examples of in
previous chapters. Not it is time to make your own modules from scratch.
Previously you have been using di↵erent modules, libraries or packages created
by the Python organization or by others. Here you will create your own modules
from scratch.
71
The formula for converting from Fahrenheit to Celsius is:
8.2 Exercises
Below you find di↵erent 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
72
and degrees.
Create two functions that convert from radians to degrees (r2d(x)) and from
degrees to radians (d2r(x)) respectively.
Test the functions to make sure that they work as expected. You can choose to
make a new .py file to test these functions or you can use the Console window.
[End of Exercise]
73
Chapter 9
9.1 Introduction
Python has several functions for creating, reading, updating, and deleting files.
The key function for working with files in Python is the open() function.
• ”x” - Create - Creates the specified file, returns an error if the file exists
• ”w” - Write - Opens a file for writing, creates the file if it does not exist
• ”r” - Read - Default value. Opens a file for reading, error if the file does
not exist
• ”a” - Append - Opens a file for appending, creates the file if it does not
exist
In addition you can specify if the file should be handled as binary or text mode
• ”x” - Create - Creates the specified file, returns an error if the file exists
• ”w” - Write - Opens a file for writing, creates the file if it does not exist
• ”a” - Append - Opens a file for appending, creates the file if it does not
exist
74
To write to an Existing file, you must add a parameter to the open() function:
• ”w” - Write - Opens a file for writing, creates the file if it does not exist
• ”a” - Append - Opens a file for appending, creates the file if it does not
exist
1 f = open ( ” m y f i l e . t x t ” , ”x” )
2
3 data = ” Helo World”
4
5 f . w r i t e ( data )
6
7 f . close ()
Listing 9.1: Write Data to a File
[End of Example]
• ”r” - Read - Default value. Opens a file for reading, error if the file does
not exist
1 f = open ( ” m y f i l e . t x t ” , ” r ” )
2
3 data = f . r e a d ( )
4
5 p r i n t ( data )
6
7 f . close ()
Listing 9.2: Read Data from a File
[End of Example]
75
1 data = [ 1 . 6 , 3 . 4 , 5 . 5 , 9 . 4 ]
2
3 f = open ( ” m y f i l e . t x t ” , ”x” )
4
5 f o r v a l u e i n data :
6 record = s t r ( value )
7 f . write ( record )
8 f . w r i t e ( ” \n” )
9
10 f . close ()
Listing 9.3: Logging Data to File
[End of Example]
1 f = open ( ” m y f i l e . t x t ” , ” r ” )
2
3 for record in f :
4 r e c o r d = r e c o r d . r e p l a c e ( ” \n” , ” ” )
5 print ( record )
6
7 f . close ()
Listing 9.4: Read Logged Data from File
[End of Example]
9.6 Exercises
Below you find di↵erent 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!
76
[End of Exercise]
You can use the Random Generator in Python. An example of how to use the
Random Generator is shown below:
1 im po rt random
2 f o r x in range (10) :
3 data = random . r a n d i n t ( 1 , 3 1 )
4 p r i n t ( data )
Listing 9.5: Read Data from a File
Make sure to log both the time and the temperature value
You should also plot the data you read from the File.
[End of Exercise]
77
Chapter 10
10.1.2 Exceptions
Even if a statement or expression is syntactically correct, it may cause an error
when an attempt is made to execute it. Errors detected during execution are
called exceptions and are not unconditionally fatal: you will soon learn how to
handle them in Python programs. Most exceptions are not handled by programs,
however, and result in error messages as shown here:
1 >>> 10 ⇤ ( 1 / 0 )
2 Traceback ( most r e c e n t c a l l last ) :
3
4 F i l e ”<ipy thon i n p u t 2 0b 2 8 0 f 3 6 8 3 5 c >” , l i n e 1 , i n <module>
5 10 ⇤ ( 1 / 0 )
6
7 Z e r o D i v i s i o n E r r o r : d i v i s i o n by z e r o
or:
1 >>> ’ 2 ’ + 2
2 Traceback ( most r e c e n t c a l l last ) :
3
79
4 F i l e ”<ipy thon i n p u t 3 d2b23a1db757>” , l i n e 1 , i n <module>
5 ’2 ’ + 2
6
7 TypeError : must be s t r , not i n t
• The try block lets you test a block of code for errors.
When an error occurs, or exception as we call it, Python will normally stop and
generate an error message.
1 try :
2 10 ⇤ ( 1 / 0 )
3 except :
4 p r i n t ( ”The c a l c u l a t i o n f a i l e d ” )
or:
1 try :
2 print (x)
3 except :
4 p r i n t ( ”x i s not d e f i n e d ” )
The finally block, if specified, will be executed regardless if the try block raises
an error or not.
Example:
80
1 x=2
2
3 try :
4 print (x)
5 e x c e p t NameError :
6 p r i n t ( ”x i s not d e f i n e d ” )
7 except :
8 p r i n t ( ” Something i s wrong ” )
9 finally :
10 p r i n t ( ”The Program i s f i n i s h e d ” )
In general you should use try - except - finally when you try to open a File, read
or write to Files, connect to a Database, etc.
Example:
1 try :
2 f = open ( ” m y f i l e . t x t ” )
3 f . w r i t e ( ”Lorum Ipsum ” )
4 except :
5 p r i n t ( ” Something went wrong when w r i t i n g t o t h e f i l e ” )
6 finally :
7 f . close ()
81
Chapter 11
Debugging in Python
Debuggers are software tools which enable the programmer to monitor the ex-
ecution of a program, stop it, restart it, set breakpoints, and change values in
memory. The term debugger can also refer to the person who is doing the de-
bugging.
As a programmer, one of the first things that you need for serious program
development is a debugger.
Python has a built-in debugger that can be used if you are coding Python with
a basic text editor and running your Python programs from the command line.
A better option is to use the Debugging features integrated in your Python Ed-
itor. Debugging is typically integrated with the Python Editor you are using.
82
Chapter 12
A package contains all the files you need for a module. Modules are Python
code libraries you can include in your project.
Since Python is open source you can find thousands of Python Packages that
you can install and use in your Python programs.
You can use a Python Distribution like Anaconda Distribution (or similar
Python Distributions) to download and install many common Python Pack-
ages as mentioned previously.
If you do not have PIP installed, you can download and install it from this page:
[Link]
PIP is typically used from the Command Prompt (Windows) or Terminal win-
dow (macOS).
1 p i p i n s t a l l packagename
Some Python Editors also have a graphical way of installing Python Packages,
like, e.g., Visual Studio.
83
Part III
84
Chapter 13
Introduction to Python
Environments and
Distributions
Python is open source and everybody can bundle and distribute Python and
di↵erent Python Packages.
A Python environment is a context in which you run Python code and includes
Python Packages.
• Anaconda
• Enthought Canopy
• WinPython
• etc.
85
But you can also install the core Python from:
[Link]
Then install the additional Python Packages you need by using PIP.
[Link]
13.1.1 PIP
Web:
[Link]
PIP is typically used from the Command Prompt (Windows) or Terminal win-
dow (macOS).
1 p i p i n s t a l l packagename
13.1.2 Conda
Conda is an open source package management system and environment man-
agement system that runs on Windows, macOS and Linux. Conda installs, runs
and updates packages and their dependencies.
The Conda package and environment manager is included in all versions of Ana-
conda.
Conda was created for Python programs, but it can package and distribute soft-
ware for any language.
Conda allows you to to also create separate environments containing files, pack-
ages and their dependencies that will not interact with other environments.
86
Web:
[Link]
Web:
[Link]
Python Virtual Environments have their own installation directories and they
don’t share libraries with other virtual environments.
Python ”Virtual Environments” is handy when you have di↵erent Python appli-
cations that needs di↵erent versions of Python or di↵erent version of the Python
Packages you are using.
87
Chapter 14
Anaconda
Web:
[Link]
Wikipedia:
[Link] P ythond istribution)
88
Figure 14.1: Anaconda Navigator
89
Chapter 15
Enthought Canopy
Canopy is freely available to all users under the Canopy license. Canopy pro-
vides access to several hundreds Python packages, including NumPy, SciPy,
Pandas, Matplotlib, and IPython.
Web:
[Link]
90
Chapter 16
Python Editors
An Editor is a program where you create your code (and where you can run
and test it). Most Editors have also features for Debugging and IntelliSense.
In theory, you can use Windows Notepad for creating Python programs, but
in practice it is impossible to create programs without having an editor with
Debugging, IntelliSense, color formatting, etc.
For simple Python programs you can use the IDLE Editor, but for more ad-
vanced programs a better editor is recommended.
• Spyder
• Visual Studio Code
• Visual Studio
• PyCharm
• Wing
• JupyterNotebook
We will give an overview of these Code Editors in the next chapters.
I guess hundreds of di↵erent editors can be used for Python Programming, ei-
ther out of the box or if you install an additional Extension that makes sure
you can use Python in that editor.
If you already have a favorite Code Editor, it is a good change you can use that
one for Python programming.
Which editor you should use depends on your background, what kind of code
editors you have used previously, your programming skills, what your are going
to develop in Python, etc.
92
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.
93
Chapter 17
Spyder
94
• Variable Explorer
• etc.
Web:
[Link]
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:
[Link]
95
Chapter 18
Web:
[Link]
Wikipedia:
[Link] tudioC ode
96
18.2 Python in Visual Studio Code
In addition to Visual Studio Code you need to install the Python extension for
Visual Studio Code.
You must install a Python interpreter yourself separately from the extension.
For a quick install, use Python from [Link].
[Link]
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:
[Link]
97
Chapter 19
Visual Studio
You could say Visual Studio is the big brother of Visual Studio Code.
Visual Studio (from 2017), has integrated support for Python, it is called
”Python Support in Visual Studio”.
Web:
[Link]
Wikipedia:
[Link] isualS tudio
98
Figure 19.1: Using Visual Studio as Python Editor
Note that Python support is available only on Visual Studio for Windows. If
you use Mac and Linux, you need to use Visual Studio Code. You could say
Visual Studio Code is a down-scaled version of Visual Studio.
Visual Studio (from 2017), has integrated support for Python, it is called
”Python Support in Visual Studio”. Even if it is integrated, you need to manu-
ally select which components you want to install on your computer. Make sure
to download and run the latest Visual Studio 2017 installer for Windows.
when you run the Visual Studio installer (either for the first time or if you
already have installed Visual Studio 2017 and want to modify it) the window
shown in Figure 19.2 pops up.
The installer presents you with a list of so called workloads, which are groups of
related options for specific development areas. For Python, select the ”Python
development” workload and select Install (Figure 19.3).
99
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 di↵erent Desktop GUI applications. We can
also create Games.
100
Figure 19.4: Python Interactive
We start by creating a basic Hello World Python Application. See Figure 19.1.
Select File - New - Project... The New Project window pops up. See Figure 19.5.
1 p r i n t ( ” H e l l o World” )
Hit F5 (our click the green arrow) in order to run or execute the Python program.
You can also right click on the file and select ”Start without Debugging”.
[End of Example]
1 im po rt m a t p l o t l i b . p y p l o t a s p l t
2 im po rt numpy a s np
3
4 xstart = 0
5 x s t o p = 2⇤ np . p i
6 increment = 0.1
7
8 x = np . a r a n g e ( x s t a r t , xstop , i n c r e m e n t )
9
10 y = np . s i n ( x )
11
12 plt . plot (x , y)
13 p l t . t i t l e ( ’ y=s i n ( x ) ’ )
101
Figure 19.5: New Python Project
14 plt . xlabel ( ’x ’ )
15 plt . ylabel ( ’y ’ )
16 plt . grid ()
17 plt . a x i s ( [ 0 , 2⇤ np . pi , 1, 1 ] )
18 plt . show ( )
In this example we use the Matplotlib package for plotting, so we need to have
that package installed on the computer. You can install the Matplotlib package
in di↵erent 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 di↵er-
ent Python Environments. See Figure 19.9.
102
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]
103
Figure 19.7: Select your Python Environment
104
Figure 19.9: Installing Python Packages for di↵erent Python Environments from
Visual Studio
105
Chapter 20
PyCharm
Web:
[Link]
Wikipedia:
[Link]
Anaconda and JetBrains also have a collaboration and o↵er what they call Py-
Charm for Anaconda. You can download it here:
106
[Link]
We have code editors like Visual Studio and Visual Studio Code which can be
used for many di↵erent programming languages by installing di↵erent types of
plugins.
Editors like Spyder and PyCharm are tailor-made editors for the Python lan-
guage.
Spyder is light-weight IDE typically used for scientific use. PyCharm on the
other hand is full-blown IDE for software development in general by using the
Python language. It supports many plugins, it’s easier to program Django, etc.
107
Chapter 21
• Wing 101 – a very simplified free version, for teaching beginning pro-
grammers
• Wing Personal – free version that omits some features, for students and
hobbyists
• Wing Pro – a full-featured commercial (paid) version, for professional
programmers
Web:
[Link]
108
Wikipedia:
[Link] DE
109
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.
114
1 from math im por t s i n , c o s
2
3 x = 3.14
4 y = sin (x)
5 print (y)
6
7 y = cos (x)
8 print (y)
[End of Example]
There are advantages and disadvantages with the di↵erent approaches. In your
program you may need to use functions from many di↵erent 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 di↵erent
libraries have some functions with the same name but di↵erent 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:
[Link]
115
23.1.1 Exercises
Below you find di↵erent 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]
ln (ax2 + bx + c) sin(ax2 + bx + c)
f (x) = (23.2)
4⇡x2 + cos(x 2)(ax2 + bx + c)
Tip! You should split the expressions into di↵erent 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]
116
Figure 23.1: Right-angled triangle
c 2 = a 2 + b2 (23.3)
1 def pythagoras (a , b)
2 ...
3 ...
4 return 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.
117
[End of Exercise]
[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”,
Mean:
N
1 X 2.2 + 4.5 + 6.2 + 3.6 + 2.6 19.1
x̄ = xi = = = 3.82 (23.6)
N i=1 5 5
118
[End of Example]
Variance:
N
1 X
var(x) = (xi x̄)2 (23.7)
N i=1
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.
v
u N
p u1 X
std(x) = = var = t (xi x̄)2 (23.8)
N i=1
2
We have that = var(x)
For more information about the functions in the Python Standard Library,
see:
[Link]
1 im po rt s t a t i s t i c s a s s t
2
3 data = [ 1.0 , 2.5 , 3.25 , 5 . 7 5 ]
4
5 #Mean o r Average
6 m = s t . mean ( data )
7 p r i n t (m)
8
9 # Standard D e v i a t i o n
10 s t d e v = s t . s t d e v ( data )
119
11 print ( st dev )
12
13 # Median
14 med = s t . median ( data )
15 p r i n t ( med )
16
17 # Variance
18 v a r = s t . v a r i a n c e ( data )
19 p r i n t ( var )
Listing 23.1: Statistics functions in Python
[End of Example]
IMPORTANT: Do not name your file ”[Link]” 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.
Below you find some examples how to use some of the statistics functions in
NumPy:
1 im po rt numpy a s np
2
3 data = [ 1.0 , 2.5 , 3.25 , 5 . 7 5 ]
4
5 #Mean o r Average
6 m = np . mean ( data )
7 p r i n t (m)
8
9 # Standard D e v i a t i o n
10 s t d e v = np . s t d ( data )
11 print ( st dev )
12
13 # Median
14 med = np . median ( data )
15 p r i n t ( med )
16
17 # Minimum Value
18 minv = np . min ( data )
19 p r i n t ( minv )
20
21 # Maxumum Value
22 maxv = np . max( data )
23 p r i n t ( maxv )
Listing 23.2: Statistics using the NumPy Library
120
[End of Example]
Create your own Statistics Module in Python (e.g., ”[Link]) and then
create a Python Script (e.g., ”[Link]) where you test these func-
tions.
You should at least implement functions for mean, variance, standard deviation,
minimum and maximum.
[End of Exercise]
Note! Most of the trigonometric functions require that the angle is expressed in
radians.
Example 23.3.1. Trigonometric Functions in Math module
1 im po rt math a s mt
2
3 x = 2⇤mt . p i
4
5 y = mt . s i n ( x )
6 print (y)
7
8 y = mt . c o s ( x )
9 print (y)
10
11 y = mt . tan ( x )
12 print (y)
Listing 23.3: Trigonometric Functions in Math module
Here we have used the Math module in the Python Standard Library.
For more information about the functions in the Python Standard Library,
see:
[Link]
121
[End of Example]
1 im po rt math a s mt
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 xdata = [ ]
5 ydata = [ ]
6
7 f o r x in range (0 , 10) :
8 xdata . append ( x )
9 y = mt . s i n ( x )
10 ydata . append ( y )
11
12 p l t . p l o t ( xdata , ydata )
13 p l t . show ( )
Listing 23.4: Plotting Trigonometric Functions
In the example we have plotted sin(x), we can easily extend the program to plot
cos(x), etc.
For more information about the functions in the Python Standard Library,
see:
[Link]
[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 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 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 )
122
11 plt . plot (x , y)
12 plt . t i t l e ( ’ y=s i n ( x ) ’ )
13 plt . xlabel ( ’x ’ )
14 plt . ylabel ( ’y ’ )
15 plt . grid ()
16 plt . a x i s ( [ 0 , 2⇤ np . pi , 1, 1 ] )
17 plt . show ( )
18
19 y = np . c o s ( x )
20 plt . plot (x , y)
21 p l t . t i t l e ( ’ y=c o s ( x ) ’ )
22 plt . xlabel ( ’x ’ )
23 plt . ylabel ( ’y ’ )
24 plt . grid ()
25 p l t . a x i s ( [ 0 , 2⇤ np . pi , 1, 1 ] )
26 p l t . show ( )
27
28 y = np . tan ( x )
29 plt . plot (x , y)
30 p l t . t i t l e ( ’ y=tan ( x ) ’ )
31 plt . xlabel ( ’x ’ )
32 plt . ylabel ( ’y ’ )
33 plt . grid ()
34 p l t . a x i s ( [ 0 , 2⇤ np . pi , 1, 1 ] )
35 p l t . show ( )
Listing 23.5: Trigonometric Functions using NumPy
[End of Example]
We have that:
123
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 di↵erent 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
c 2 = a 2 + 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 , ’ c o s ’ )
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.
124
[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 di↵erent subplots).
Make sure to add labels and a legend and use di↵erent line styles and colors for
the plots.
[End of Exercise]
23.4 Polynomials
A polynomial is expressed as:
p(x) = p1 xn + p2 xn 1
+ ... + pn x + pn+1 (23.17)
Web:
[Link]
Other Resources:
125
126
127