0% found this document useful (0 votes)
2 views85 pages

Python Programming

The document provides an overview of variables in Python, explaining how to create and use them, as well as their dynamic typing nature. It covers numeric types, strings, and basic rules for naming variables, along with examples of calculations and built-in functions. Additionally, it introduces Python libraries and modules, highlighting the importance of importing them for extended functionality.

Uploaded by

prin.nattaseth
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views85 pages

Python Programming

The document provides an overview of variables in Python, explaining how to create and use them, as well as their dynamic typing nature. It covers numeric types, strings, and basic rules for naming variables, along with examples of calculations and built-in functions. Additionally, it introduces Python libraries and modules, highlighting the importance of importing them for extended functionality.

Uploaded by

prin.nattaseth
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

ส ป ว อ 4.

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.

We use the basic IDLE editor (or another Python Editor)

Example 4.1.1. Hello World Example


Lets open your Python Editor and type the following:

1 p r i n t ( ” H e l l o World ! ” )
Listing 4.1: Hello World Python Example

[End of Example]

4.1.1 Get Help


An extremely useful command is help(), which enters a help functionality to
explore all the stu↵ python lets you do, right from the interpreter.

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

Example 4.2.2. Calculations in Python


We can use variables in a calculation like this:
1 x = 3
2 y = 3⇤ x
3 print (y)
Listing 4.3: Using and Printing Variables in Python

We can implementing the formula y = ax + b like this:


1 a = 2
2 b = 5
3 x = 3
4
5 y = a ⇤x + b
6
7 print (y)
Listing 4.4: Calculations in Python

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.

Figure 4.1: Basic Python

Here are some basic rules for Python variables:


• A variable name must start with a letter or the underscore character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters (A-z, 0-9) and
underscores
• Variable names are case-sensitive, e.g., amount, Amount and AMOUNT
are three di↵erent variables.

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.

Example 4.2.3. Numeric Types in Python

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):

Figure 4.2: Variable Editor in Spyder

[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”).

Example 4.2.4. Plotting in Python


Below we see examples of using strings in Python:

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]

4.2.3 String Input


Python allows for command line input.

That means we are able to ask the user for input.

Example 4.2.5. Plotting in Python


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 pr in t ( ” Hello , ” + x )
Listing 4.8: String Input

[End of Example]

4.3 Built-in Functions


Python consists of lots of built-in functions. Some examples are the print(9
function that we already have used (perhaps without noticing it is actually a
Built-in function).

Python also consists of di↵erent Modules, Libraries or Packages. These Mod-


ules, Libraries or Packages consists of lots of predefined functions for di↵erent
topics or areas, such as mathematics, plotting, handling database systems, etc.
See Section 4.4 for more information and details regarding this.

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.

Example 4.4.1. Using the math module


We create some basic examples how to use a Library, a Package or a Module:

If we need only the sin() function we can do like this:


1 from math im por t s i n
2
3 x = 3.14
4 y = sin (x)
5
6 print (y)

If we need a few functions we can do like this


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)

If we need many functions we can do like this:


1 from math im por t ⇤
2
3 x = 3.14
4 y = sin (x)
5 print (y)
6
7 y = cos (x)
8 print (y)

We can also use this alternative:


1 im po rt math
2
3 x = 3.14
4 y = math . s i n ( x )
5
6 print (y)

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]

4.5 Using Python Libraries, Packages and Mod-


ules
Rather than having all of its functionality built into its core, Python was de-
signed to be highly extensible. This approach has advantages and disadvantages.
An disadvantage is that you need to install these packages separately and then
later import these modules in your code.

Some important packages are:


• NumPy - NumPy is the fundamental package for scientific computing
with Python
• SciPy - SciPy is a free and open-source Python library used for scientific
computing and technical computing. SciPy contains modules for optimiza-
tion, linear algebra, integration, interpolation, special functions, FFT, sig-
nal and image processing, ODE solvers and other tasks common in science
and engineering.
• Matplotlib - Matplotlib is a Python 2D plotting library

42
Lots of other packages exists, depending on what you are going to solve.

These packages need to be downloaded and installed separately, or you choose


to use, e.g., a distribution package like Anaconda.

Here you find an overview of the NumPy library:


[Link]

Here you find an overview of the SciPy library:


[Link]

Here you find an overview of the Matplotlib library:


[Link]

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]

4.5.1 Python Packages


In addition to the Python Standard Library, there is a growing collection of sev-
eral thousand components (from individual programs and modules to packages
and entire application development frameworks), available from the Python
Package Index.

Python Package Index (PYPI):


[Link]

Here you can download and install individual Python packages.


An easy alternative is the Anaconda Distribution, where many of the most used
Python packages are included.

Anaconda:
[Link]

4.6 Plotting in Python


Typically you need to create some plots or charts. In order to make plots or
charts in Python you will need an external library. The most used library is
Matplotlib.

Matplotlib is a Python 2D plotting library

Here you find an overview of the Matplotlib library:


[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:

Example 4.6.1. Plotting in Python


In this example we have to arrays with data. We want to plot x vs. y. We
can assume x is a time series and y is the corresponding temperature i degrees
Celsius.
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
3 x = [1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10]
4
5 y = [ 5 , 2 ,4 , 4 , 8 , 7 , 4 , 8 , 10 , 9 ]
6
7 plt . plot (x , y)
8 plt . x l a b e l ( ’ Time ( s ) ’ )
9 plt . y l a b e l ( ’ Temperature ( degC ) ’ )
10 plt . show ( )

We get the following plot:


We can also write like this:
1 from m a t p l o t l i b . p y p l o t i mp ort ⇤
2
3 x = [1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10]
4 y = [ 5 , 2 ,4 , 4 , 8 , 7 , 4 , 8 , 10 , 9 ]
5
6 plot (x , y)
7 x l a b e l ( ’ Time ( s ) ’ )
8 y l a b e l ( ’ Temperature ( degC ) ’ )
9 show ( )

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]

We have used 4 basic plotting function in the Matplotlib library:

• plot()
• xlabel()
• ylabel()

• show()

Example 4.6.2. Plotting a Sine Curve

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 ( )

This gives the following plot (see Figure 4.4):


A better solution will then be:

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 ( )

This gives the following plot (see Figure 4.5):


If you want grids you can use the grid() function.

[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.

Example 4.6.3. Creating Subplots

47
Figure 4.5: Plotting a Sine function in Python - Better Implementation

We will create and plot sin() and cos() in 2 di↵erent subplots.


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 z = np . c o s ( x )
13
14
15 plt . subplot (2 ,1 ,1)
16 plt . plot (x , y , ’g ’ )
17 plt . t i t l e ( ’ sin ’ )
18 plt . xlabel ( ’x ’ )
19 plt . ylabel ( ’ sin (x) ’ )
20 plt . grid ()
21 plt . show ( )
22
23
24 plt . subplot (2 ,1 ,2)
25 plt . plot (x , z , ’ r ’ )
26 plt . t i t l e ( ’ cos ’ )
27 plt . xlabel ( ’x ’ )
28 plt . ylabel ( ’ cos (x) ’ )
29 plt . grid ()
30 plt . show ( )

[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!

Exercise 4.6.1. Create sin(x) and cos(x) in 2 di↵erent plots


Create sin(x) and cos(x) in 2 di↵erent plots.

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.

5.1 If ... Else


An ”if statement” is written by using the if keyword.

Here are some Examples how you use a If sentences in Python:


Example 5.1.1. Using For Loops in Python

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:

Example 5.2.1. Using For Loops 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 define an array like this:


1 data = [ 1 . 6 , 3 . 4 , 5 . 5 , 9 . 4 ]

You can also use text like this:


1 c a r l i s t = [ ” Volvo ” , ” T e s l a ” , ” Ford ” ]

You can use Arrays in Loops like this:


1 f o r x i n data :
2 print (x)

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 ]

You can use the append() method to add an element to an array:


1 data . append ( 1 1 . 4 )

[End of Example]

You have many built in methods you can use in combination with arrays, like
sort(), clear(), copy(), count(), insert(), remove(), etc.

You should look test all these methods.

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.

Example 5.3.1. Using For Loops 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

The range() function is handy yo use in For Loops:


1 N = 10
2
3 f o r x i n r a n g e (N) :
4 print (x)

The range() function returns a sequence of numbers, starting from 0 by default,


and increments by 1 (by default), and ends at a specified number.

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
4 f o r x in range ( s t a r t , stop ) :
5 print (x)

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]

Example 5.3.2. Using For Loops for Summation of Data


You typically want to use a For loop for find the sum of a given data set.
1 data = [ 1 , 5 , 6 , 3 , 1 2 , 3 ]
2
3 sum = 0
4
5 #Find t h e Sum o f a l l t h e numbers
6 f o r x i n data :
7 sum = sum + x
8
9 p r i n t ( sum )
10
11 #Find t h e Mean o r Average o f a l l t h e numbers
12
13 N = l e n ( data )
14
15 mean = sum/N
16
17 p r i n t ( mean )

This gives the following results:


1 30
2 5.0

[End of Example]

Example 5.3.3. Implementing Fibonacci Numbers Using a For Loop in Python


Fibonacci numbers are used in the analysis of financial markets, in strategies
such as Fibonacci retracement, and are used in computer algorithms such as the
Fibonacci search technique and the Fibonacci heap data structure.
They also appear in biological settings, such as branching in trees, arrangement
of leaves on a stem, the fruitlets of a pineapple, the flowering of artichoke, an
uncurling fern and the arrangement of a pine cone.

In mathematics, Fibonacci numbers are the numbers in the following sequence:


0, 1, 1, 2 ,3, 5, 8, 13, 21, 34, 55, 89, 144, . . .

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)

with seed values:

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

Another alternative solution:


1 N = 10
2
3 fib = [ ]
4
5 f o r k i n r a n g e (N) :
6 f i b . append ( 0 )
7
8 fib [0] = 0
9 fib [1] = 1
10

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

Another alternative solution:


1 im po rt numpy a s np
2
3
4 N = 10
5
6 f i b = np . z e r o s (N)
7
8 fib [0] = 0
9 fib [1] = 1
10
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.9: Fibonacci Numbers Using a For Loop in Python - Alt4

[End of Example]

5.3.1 Nested For Loops


In Python and other programming languages you can use one loop inside an-
other loop.

Syntax for nested For loops in Python:


1 f o r i t e r a t i n g v a r in sequence :
2 f o r i t e r a t i n g v a r in sequence :
3 statements ( s )
4 statements ( s )

Simple example:
1 f o r i in range (1 , 10) :
2 f o r k in range (1 , 10) :
3 print ( i , k)

Exercise 5.3.1. Prime Numbers


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

57
By definition a prime number has both 1 and itself as a divisor. If it has any
other divisor, it cannot be prime.

A natural number (1, 2, 3, 4, 5, 6, etc.) is called a prime number (or a prime) if


it is greater than 1 and cannot be written as a product of two natural numbers
that are both smaller than it.

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]

5.4 While Loops


The while loop repeats a group of statements an indefinite number of times
under control of a logical condition.

Example 5.4.1. Using While Loops in Python

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!

Exercise 5.5.1. Plot of Dynamic System

Given the autonomous system:


ẋ = ax (5.2)
Where:
1
a=
T

58
where T is the time constant.

The solution for the di↵erential equation is:

x(t) = eat x0 (5.3)

Set T=5 and the initial condition x(0)=1.

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.

Previously we have been using many of the built-in functions in Python

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.

Some programming languages uses the term Method instead of a Function.


Functions and Methods behave in the same manner, but you could say that
Methods are functions that belongs to a Class. We will learn more about Classes
in Chapter 7.

Scripts vs. Functions

It is important to know the di↵erence between a Script and a Function.

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 . . .

Example 6.1.1. Create a Function in a separate File


Below you see a simple function created in Python:
1 d e f add ( x , y ) :
2
3 return x + y
Listing 6.1: Basic Python Function

The function adds 2 numbers. The name of the function is add, and it returns
the answer using the return statement.

The statement return [expression] exits a function, optionally passing back an


expression to the caller. A return statement with no arguments is the same as
return None.

Note that you need to use a colon ”:” at the end of line where you define the
function.

Note also the indention used.

1 d e f add ( x , y ) :

Here you see a Python script where we use the function:


1 d e f add ( x , y ) :
2
3 return x + y
4
5
6 x = 2
7 y = 5
8
9 z = add ( x , y )
10
11 print ( z )
Listing 6.2: Creating and Using a Python Function

61
[End of Example]

Example 6.1.2. Create a Function in a separate File


We start by creating a separate Python File ([Link]) for the function:
1 def average (x , y) :
2
3 r e t u r n ( x + y ) /2
Listing 6.3: Function calculating the Average

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]

6.2 Functions with multiple return values


Typically we want to return more than one value from a function.

Example 6.2.1. Create a Function Function with multiple return values


Create the following example:
1 def stat (x) :
2
3 totalsum = 0
4
5 #Find t h e Sum o f a l l t h e numbers
6 f o r x i n data :
7 totalsum = totalsum + x
8
9
10 #Find t h e Mean o r Average o f a l l t h e numbers
11
12 N = l e n ( data )
13
14 mean = t o t a l s u m /N
15
16
17 r e t u r n t o t a l s u m , mean
18
19
20

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!

Exercise 6.3.1. Create Python Function

Create a function calcaverage that finds the average of two numbers.

[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.

It is quite easy to convert from radians to degrees or from degrees to radians.

We have that:

2⇡[radians] = 360[degrees] (6.1)


This gives:
180
d[degrees] = r[radians] ⇥ ( ) (6.2)

and

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.

These functions should be saved in one Python file .py.

Test the functions to make sure that they work as expected.

63
[End of Exercise]

Exercise 6.3.3. Create a Function that Implementing Fibonacci Numbers


Fibonacci numbers are used in the analysis of financial markets, in strategies
such as Fibonacci retracement, and are used in computer algorithms such as the
Fibonacci search technique and the Fibonacci heap data structure.
They also appear in biological settings, such as branching in trees, arrangement
of leaves on a stem, the fruitlets of a pineapple, the flowering of artichoke, an
uncurling fern and the arrangement of a pine cone.

In mathematics, Fibonacci numbers are the numbers in the following sequence:


0, 1, 1, 2 ,3, 5, 8, 13, 21, 34, 55, 89, 144, . . .

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.

In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the


recurrence relation

fn = fn 1 + fn 2 (6.4)

with seed values:

f0 = 0, f1 = 1

Create a Function that Implementing the N first Fibonacci Numbers

[End of Exercise]

Exercise 6.3.4. Prime Numbers


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

By definition a prime number has both 1 and itself as a divisor. If it has any
other divisor, it cannot be prime.

A natural number (1, 2, 3, 4, 5, 6, etc.) is called a prime number (or a prime) if


it is greater than 1 and cannot be written as a product of two natural numbers
that are both smaller than it.

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 )

Then Python respond with True or False.

[End of Exercise]

65
Chapter 7

Creating Classes in Python

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.

To create a class, use the keyword class:

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>

Example 7.1.1. Simple Class Example


We will create a simple Class in Python.

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

The results will be in this case:


1 Volvo
2 Blue

66
This example don’t illustrate the good things with classes so we will create some
more examples.

[End of Example]

Example 7.1.2. Python Class


Lets create the following Python Code:
1 c l a s s Car :
2 model = ” ”
3 c o l o r = ””
4
5 c a r = Car ( )
6
7 c a r . model = ” Volvo ”
8 c a r . c o l o r = ” Blue ”
9
10 p r i n t ( c a r . c o l o r + ” ” + c a r . model )
11
12 c a r . model = ” Ford ”
13 c a r . c o l o r = ” Green ”
14
15 p r i n t ( c a r . c o l o r + ” ” + c a r . model )
Listing 7.2: Python Class example

You should try these examples.

[End of Example]

7.2 The init () Function


In Python all classes have a built-in function called init (), which is always
executed when the class is being initiated.
In many other OOP languages we call this the Constructor.
Exercise 7.2.1. The init () Function
We will create a simple example where we use the init () function to illustrate
the principle.

We change our previous Car example like this:


1 c l a s s Car :
2 def init ( s e l f , model , c o l o r ) :
3 s e l f . model = model
4 s e l f . color = color
5
6 c a r 1 = Car ( ” Ford ” , ” Green ” )
7
8 p r i n t ( c a r 1 . model )
9 print ( car1 . c o l o r )
10
11

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

Lets extend the Class by defining a Function as well:


1 # Defining the Class Car
2 c l a s s Car :
3 def init ( self , model , c o l o r ) :
4 s e l f . model = model
5 s e l f . color = color
6
7 def displayCar ( s e l f ) :
8 p r i n t ( s e l f . model )
9 print ( s e l f . color )
10
11
12 # Lets s t a r t using the Class
13
14 c a r 1 = Car ( ” T e s l a ” , ”Red” )
15
16 car1 . displayCar ()
17
18
19 c a r 2 = Car ( ” Ford ” , ” Green ” )
20
21 p r i n t ( c a r 2 . model )
22 print ( car2 . c o l o r )
23
24
25 c a r 3 = Car ( ” Volvo ” , ” Blue ” )
26
27 p r i n t ( c a r 3 . model )
28 print ( car3 . c o l o r )
29
30 c a r 3 . c o l o r=” Black ”
31
32 car3 . displayCar ()
Listing 7.4: Python Class with Function

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]

Exercise 7.2.2. Create the Class in a separate Python file


We start by creating the Class and then we save the code in ”[Link]”:
1 # Defining the Class Car
2 c l a s s Car :
3 def init ( self , model , c o l o r ) :
4 s e l f . model = model
5 s e l f . color = color
6
7 def displayCar ( s e l f ) :
8 p r i n t ( s e l f . model )
9 print ( s e l f . color )
Listing 7.5: Define Python Class in separate File

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

Notice the following line at the top:


1 from Car im por t Car

[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!

Exercise 7.3.1. Create Python Class


Create a Python Class where you calculate the degrees in Fahrenheit based on
the temperature in Celsius and vice versa.

The formula for converting from Celsius to Fahrenheit is:

Tf = (Tc ⇥ 9/5) + 32 (7.1)


The formula for converting from Fahrenheit to Celsius is:

Tc = (Tf 32) ⇥ (5/9) (7.2)

[End of Exercise]

70
Chapter 8

Creating Python Modules

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).

8.1 Python Modules


A module is a file containing Python definitions and statements. The file name
is the module name with the suffix .py appended.

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.

Consider a module to be the same as a code library. A file containing a set of


functions you want to include in your application.

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.

Example 8.1.1. Create your first Python Module


We will create a Python module with 2 functions. The first function should
convert from Celsius to Fahrenheit and the other function should convert from
Fahrenheit to Celsius.

The formula for converting from Celsius to Fahrenheit is:


Tf = (Tc ⇥ 9/5) + 32 (8.1)

71
The formula for converting from Fahrenheit to Celsius is:

Tc = (Tf 32) ⇥ (5/9) (8.2)

First, we create a Python module with the following functions ([Link]):


1 d e f c 2 f ( Tc ) :
2
3 Tf = ( Tc ⇤ 9 / 5 ) + 32
4 r e t u r n Tf
5
6
7 d e f f 2 c ( Tf ) :
8
9 Tc = ( Tf 32) ⇤(5/9)
10 r e t u r n Tc
Listing 8.1: Fahrenheit Functions

Then, we create a Python script for testing the functions ([Link]):


1 from f a h r e n h e i t i mp ort c 2 f , f 2 c
2
3 Tc = 0
4
5 Tf = c 2 f ( Tc )
6
7 p r i n t ( ” F a h r e n h e i t : ” + s t r ( Tf ) )
8
9
10 Tf = 32
11
12 Tc = f 2 c ( Tf )
13
14 p r i n t ( ” C e l s i u s : ” + s t r ( Tc ) )
Listing 8.2: Python Script testing the functions

The results becomes:


1 Fahrenheit : 32.0
2 Celsius : 0.0

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.

It is quite easy to convert from radians to degrees or from degrees to radians.


We have that:

2⇡[radians] = 360[degrees] (8.3)


This gives:
180
d[degrees] = r[radians] ⇥ ( ) (8.4)

and

r[radians] = d[degrees] ⇥ ( ) (8.5)
180

Create two functions that convert from radians to degrees (r2d(x)) and from
degrees to radians (d2r(x)) respectively.

These functions should be saved in one Python file .py.

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

File Handling in Python

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.

The open() function takes two parameters; Filename, and Mode.

There are four di↵erent methods (modes) for 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
• ”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

• ”t” - Text - Default value. Text mode


• ”b” - Binary - Binary mode (e.g. images)

9.2 Write Data to a File


To create a New file in Python, use the open() method, with one of the following
parameters:

• ”x” - Create - Creates the specified file, returns an error if the file exists
• ”w” - Write - Opens a file for writing, creates the file if it does not exist
• ”a” - Append - Opens a file for appending, creates the file if it does not
exist

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

Example 9.2.1. Write Data to a File

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]

9.3 Read Data from a File


To read to an existing file, you must add the following parameter to the open()
function:

• ”r” - Read - Default value. Opens a file for reading, error if the file does
not exist

Example 9.3.1. Read Data from a File

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]

9.4 Logging Data to File


Typically you want to write multiple data to the, e.g., assume you read some
temperature data at regular intervals and then you want to save the temperature
values to a File.
Example 9.4.1. Logging Data to File

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]

Example 9.4.2. Read Logged Data from File

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.5 Web Resources


Below you find di↵erent useful resources for File Handling.

Python File Handling - w3school:


[Link] ileh [Link]

Reading and Writing Files - [Link]:


[Link]

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!

Exercise 9.6.1. Data Logging


Assume you have the following data you want to log to a File as shown in Table
9.1.
Log these data to a File.

Create another Python Script that reads the same data.

76
[End of Exercise]

Exercise 9.6.2. Data Logging 2


Assume you read data from a Temperature sensor every 10 seconds for a period
of let say 5 minutes.

Log the data to a File.

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

Create another Python Script that reads the same data.

You should also plot the data you read from the File.

[End of Exercise]

77
Chapter 10

Error Handling in Python

10.1 Introduction to Error Handling


So far error messages haven’t been discussed. You could say that we have 2
kinds of errors: syntax errors and exceptions.

10.1.1 Syntax Errors


Below we see an example of syntax errors:
1 >>> p r i n t ( H e l l o World )
2 F i l e ”<ipy thon i n p u t 1 10cb182148e3>” , l i n e 1
3 p r i n t ( H e l l o World )
4 ˆ
5 SyntaxError : i n v a l i d syntax

In the example we have written print(Hello World) instead of print(”Hello


World”) and then the Python Interpreter gives us an error message.

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

10.2 Exceptions Handling


It is possible to write programs that handle selected exceptions.

In Python we can use the following built-in Exceptions Handling features:

• The try block lets you test a block of code for errors.

• The except block lets you handle the error.


• The finally block lets you execute code, regardless of the result of the try-
and except blocks.

When an error occurs, or exception as we call it, Python will normally stop and
generate an error message.

These exceptions can be handled using the try - except statements.

Some basic example:

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 ” )

You can also use multiple exceptions:


1 try :
2 print (x)
3 e x c e p t NameError :
4 p r i n t ( ”x i s not d e f i n e d ” )
5 except :
6 p r i n t ( ” Something i s wrong ” )

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

Debugging is the process of finding and resolving defects or problems within


a computer program that prevent correct operation of computer software or a
system [14].

Debuggers are software tools which enable the programmer to monitor the 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.

See the specific chapter for the di↵erent Python Editors.

82
Chapter 12

Installing and using Python


Packages

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.

12.1 What is PIP?


PIP is a package manager for Python packages, or modules if you like. PIP is
a tool for installing Python packages.

If you do not have PIP installed, you can download and install it from this page:
[Link]

PIP is typically used from the Command Prompt (Windows) or Terminal win-
dow (macOS).

Installing Python Packages:

1 p i p i n s t a l l packagename

Uninstalling Python Packages:


1 p i p u n 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

Python Environments and


Distributions

84
Chapter 13

Introduction to Python
Environments and
Distributions

Python comes with many flavours and version.

Python is open source and everybody can bundle and distribute Python and
di↵erent Python Packages.

A Python environment is a context in which you run Python code and includes
Python Packages.

An environment consists of an interpreter, a library (typically the Python Stan-


dard Library), and a set of installed packages.

These components together determine which language constructs and syntax


are valid, what operating-system functionality you can access, and which pack-
ages you can use.

You can have multiple Python Environments on your Computer.

Some of them are:

• CPython distribution available from [Link]

• Anaconda
• Enthought Canopy
• WinPython

• etc.

It is easy to start using Python by installing one of these Python Distributions.

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 Package and Environment Managers


The two most popular tools for installing Python Packages and setting up
Python environments are:

• PIP - a Python Package Manager


• Conda - a Package and Environment Manager (for Python and other lan-
guages)

13.1.1 PIP
Web:
[Link]

PIP is typically used from the Command Prompt (Windows) or Terminal win-
dow (macOS).

Installing Python Packages:

1 p i p i n s t a l l packagename

Uninstalling Python Packages:


1 p i p u n 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]

Conda is part of or integrated with the Anaconda Python Distribution.

Web:
[Link]

13.2 Python Virtual Environments


Python ”Virtual Environments” allow Python packages to be installed in an
isolated location for a particular application, rather than being installed glob-
ally.

You can have multiple Python Environments on your computer.

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

Anaconda is not an Editor, but a Python Distribution package. Spyder is in-


cluded in the Python Distribution package. You can also use Anaconda to install
other Editors or Python packages.

It is available for Windows, macOS and Linux.

Web:
[Link]

Wikipedia:
[Link] P ythond istribution)

14.1 Anaconda Navigator


Anaconda Navigator is a desktop graphical user interface (GUI) included in
Anaconda distribution that allows users to launch applications and manage
Python packages. The Anaconda Navigator can search for packages and install
them on your computer, run the packages and update them.

Figure 14.1 shows the Anaconda Navigator.

88
Figure 14.1: Anaconda Navigator

89
Chapter 15

Enthought Canopy

Enthought Canopy is a Python Platform or Python Distribution for Scientists


and Engineers.

It is available for Windows, macOS and Linux.

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.

In addition, we have the Canopy Python Editor.

Enthought Canopy is a competitor to the Anaconda Python Distribution. It is


a matter of taste who you prefer.

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.

Examples of Python Editors:

• 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.

If you want to create Web Applications or other kinds of Applications, other


Editors are probably better to use.

For a list of ”Best Python Editors”, see [15].

93
Chapter 17

Spyder

Spyder - short for ”Scientific PYthon Development EnviRonment”.

Spyder is an open source cross-platform integrated development environment(IDE)


for scientific programming in the Python language.

Figure 17.1: Spyder Editor

The Spyder editor consists of the following parts or windows:


• Code Editor window
• iPython Console window

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

Visual Studio Code

18.1 Introduction to Visual Studio Code


Visual Studio Code is a simple and easy to use editor that can be used for many
di↵erent programming languages.

Figure 18.1: Using Visual Studio Code as Python Editor

Right-Click and select ”Run Python File in Terminal”

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

19.1 Introduction to Visual Studio


Microsoft Visual Studio is an integrated development environment (IDE) from
Microsoft. It is used to develop computer programs, as well as websites, web
apps, web services and mobile apps. The default (main) programming language
in Visual studio is C, but many other programming languages are supported.

You could say Visual Studio is the big brother of Visual Studio Code.

Visual studio is available for Windows and macOS.

Visual Studio (from 2017), has integrated support for Python, it is called
”Python Support in Visual Studio”.

Web:
[Link]

Wikipedia:
[Link] isualS tudio

Go to my Web Site to learn more about Visual Studio and C programming:


[Link]

Visual Studio and C:


[Link]

19.2 Work with Python in Visual Studio


Work with Python in Visual Studio:
[Link]

98
Figure 19.1: Using Visual Studio as Python Editor

19.2.1 Make Visual Studio ready for Python Program-


ming
Visual Studio is mainly for Windows. A MacOS version of Visual Studio do
exists, but it has lot less features than the Windows edition.

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).

19.2.2 Python Interactive


To quickly test Python support, launch Visual Studio, press Alt+I (or select
from the menu: Tools - Python - Python Interactive Window) to open the
Python Interactive window. See Figure 19.4.

Lets write something like this:


1 >>> a = 2

99
Figure 19.2: Installing Python Extension for Visual Studio

Figure 19.3: Python Development Workload

2 >>> b = 5
3 >>> x = 3
4 >>> y = a ⇤x + b
5 >>> y

19.2.3 New Python Project


Lets see how we can create a Python Application.

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.

Example 19.2.1. Python Hello World Application in Visual Studio

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.

Name the project, e.g, ”PythonApplication1”.


In the Project Explorer, open the ”[Link]” file and enter the
following Python code:

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]

Example 19.2.2. Visual Studio Python Plotting


Create a new Python File by right click in the Solution Explorer and select Add
- New Item... and then select ”Empty Python File”.

Enter the following Python Code:

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 ( )

See also Figure 19.6.


Make sure to select proper Python Environment. See Figure (19.7). Visual
Studio supports multiple Python Environments.

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.

I have installed the Matplotlib package as part of the Anaconda distribution


setup, so I select ”Anaconda x.x.x” in the Python Environments window.

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

Figure 19.8: Install Python Packages from Visual Studio

104
Figure 19.9: Installing Python Packages for di↵erent Python Environments from
Visual Studio

Figure 19.10: Python Plotting Example with Visual Studio

105
Chapter 20

PyCharm

PyCharm is cross-platform, with Windows, macOS and Linux versions. The


Community Edition is free to use, while the Professional Edition (paid version)
has some extra features.

The PyCharm Editor is shown in Figure 20.1.

Figure 20.1: PyCharm Python Editor

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 Python IDE

The Wing Python IDE family of integrated development environments (IDEs)


from Wingware were created specifically for the Python programming language.

3 di↵erent version of Wing exists [12]:

• 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

Figure 21.1: Wing Python IDE

Web:
[Link]

108
Wikipedia:
[Link] DE

109
Chapter 23

Mathematics in Python

Python is a powerful tool for mathematical calculations.

If you are looking for similar using MATLAB, please take a look at these re-
sources:
[Link]

23.1 Basic Math Functions


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.

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.

Example 23.1.1. Using the math module


We create some basic examples how to use a Library, a Package or a Module:

If we need only the sin() function we can do like this:


1 from math im por t s i n
2
3 x = 3.14
4 y = sin (x)
5
6 print (y)

If we need a few functions we can do like this

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)

If we need many functions we can do like this:


1 from math im por t ⇤
2
3 x = 3.14
4 y = sin (x)
5 print (y)
6
7 y = cos (x)
8 print (y)

We can also use this alternative:


1 im po rt math
2
3 x = 3.14
4 y = math . s i n ( x )
5
6 print (y)

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]

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!

Exercise 23.1.1. Create Mathematical Expressions in Python


Create a function that calculates the following mathematical expression:
p
z = 3x2 + x2 + y 2 + eln (x) (23.1)
Test with di↵erent values for x and y.

[End of Exercise]

Exercise 23.1.2. Create advanced Mathematical Expressions in Python

Create the following expression in Python:

ln (ax2 + bx + c) sin(ax2 + bx + c)
f (x) = (23.2)
4⇡x2 + cos(x 2)(ax2 + bx + c)

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 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]

Exercise 23.1.3. Pythagoras

116
Figure 23.1: Right-angled triangle

Pythagoras theorem is as follows:

c 2 = a 2 + b2 (23.3)

Create a function that uses Pythagoras to calculate the hypotenuse of a right-


angled triangle (Figure 23.1), e.g.:

1 def pythagoras (a , b)
2 ...
3 ...
4 return c

[End of Exercise]

Exercise 23.1.4. Albert Einstein


Given the famous equation from Albert Einstein:

E = mc2 (23.4)

The sun radiates 385x1024 J/s of energy.

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.

The mass of the sun is 2x1030 kg.

117
[End of Exercise]

Exercise 23.1.5. Cylinder Surface Area


Create a function that finds the surface area of a cylinder based on the height
(h) and the radius (r) of the cylinder. See Figure ??.

Figure 23.2: cylinder

[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 + ... + xN 1 X
x̄ = = xi (23.5)
N N i=1

Example 23.2.1. Mean


Given the following dataset: 2.2, 4.5, 6.2, 3.6, 2.6

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:

Variance is a measure of the variation in a data set.

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

We typically use the symbol for standard deviation.

2
We have that = var(x)

23.2.2 Statistics functions in Python


Mathematical statistics functions in Python:
[Link]

statistics is part of the The Python Standard Library.

For more information about the functions in the Python Standard Library,
see:
[Link]

Example 23.2.2. Statistics using the statistics module in Python Standard


Library
Below you find some examples how to use some of the statistics functions in the
statistics module in Python Standard Library:

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.

Here you find an overview of the NumPy library:


[Link]

Example 23.2.3. Statistics using the NumPy Library

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]

Exercise 23.2.1. Create your own Statistics Module in Python


Using the built-in functions in the Python Standard Library or the NumPy li-
brary is straightforward.

In order to get a deeper understanding of the mathematics behind these func-


tions and to learn more Python programming, you should create your own
Statistics Module in Python.

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]

23.3 Trigonometric Functions


Python o↵ers lots of Trigonometric functions, e.g., sin, cos, tan, etc.

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]

Example 23.3.2. Plotting Trigonometric Functions


In the example above we used some of the trigonometric functiosn in basic cal-
culations.

Lets see if we are able to plot these functions.

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]

Example 23.3.3. Trigonometric Functions using NumPy


The problem with using the Trigonometric functions in the the Math module
from the Python Standard Library is that they don’t handle an array as input.

We will use the NumPy library instead because they handle arrays, in addition
to all the handy functionality in the NumPy library.

1 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

This Python script gives the plots as shown in Figure 23.3.

[End of Example]

Exercise 23.3.1. Create Python functions for converting between radians an


degrees
Since most of the trigonometric functions require that the angle is expressed in
radians, we will create our own functions in order to convert between radians
and degrees.

It is quite easy to convert from radians to degrees or from degrees to radians.

We have that:

2⇡[radians] = 360[degrees] (23.9)


This gives:
180
d[degrees] = r[radians] ⇥ ( ) (23.10)

and

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.

123
These functions should be saved in one Python file .py.

Test the functions to make sure that they work as expected.

[End of Exercise]

Exercise 23.3.2. Trigonometric functions on right triangle

Given right triangle as shown in Figure 23.4.

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.

Test the function to make sure it works properly.

Tip! We have that:

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

We may also need to use the Pythagoras’ theorem:

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]

Exercise 23.3.3. Law of Cosines

Given the triangle as shown in Figure 23.5.

Create a function where you find c using the law of cosines.

c 2 = a 2 + b2 2ab cos(C) (23.16)

Test the functions to make sure it works properly.

[End of Exercise]

Exercise 23.3.4. Plotting Trigonometric Functions

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)

where p1 , p2 , p3 , ... are the coefficients of the polynomial.

We will use the Polynomial Module in the NumPy Package.

Web:
[Link]

Other Resources:

Python Advanced Course Topics - Polynomials:


[Link] lassi np [Link]

125
126

Figure 23.3: Trigonometric Functions


Figure 23.4: Right Triangle

Figure 23.5: Law of Cosines

127

You might also like