Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
8 views

Python Programming-57-84

The document discusses creating and using functions in Python. It begins with an introduction to functions, explaining that a function is a block of code that runs when called. Functions can accept parameters as input and return outputs. The document then provides examples of defining functions using the def keyword in Python, and explains how to create a function in a separate file.

Uploaded by

dyner24tests
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Python Programming-57-84

The document discusses creating and using functions in Python. It begins with an introduction to functions, explaining that a function is a block of code that runs when called. Functions can accept parameters as input and return outputs. The document then provides examples of defining functions using the def keyword in Python, and explains how to create a function in a separate file.

Uploaded by

dyner24tests
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

5.

3 For Loops
A For loop is used for iterating over a sequence. I guess all your programs will
use one or more For loops. So if you have not used For loops before, make sure
to learn it now.

Below you see a basic example how you can use a For loop in Python:
1 f o r i in range (1 , 10) :
2 print ( i )

The For loop is probably one of the most useful feature in Python (or in any
kind of programming language). Below you will see different examples how you
can use a For loop in Python.

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 for 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 different 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 different self-paced Exercises that you should go through and
solve on your own. The only way to learn Python is to do lots of Exercises!

Exercise 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 differential 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 different
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 difference 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 (myfunctions.py) 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., testaverage.py) where we use the
function we created:
1 from m y f u n c t i o n s im po rt a v e r a g e
2
3 a = 2
4 b = 3
5
6 c = average (a , b)
7
8 print ( c )
Listing 6.4: Test of Average function

[End of Example]

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 different self-paced Exercises that you should go through and
solve on your own. The only way to learn Python is to do lots of Exercises!

Exercise 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 different ways, but one way is to
use 2 nested For Loops.

64
Create a Python function where you check if a given number is a prime number
or not.

You can check the function in the Command Window like this:
1 number = 4
2 c h e c k i f p r i m e ( number )

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 ”Car.py”:
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 (testCar.py) 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 different self-paced Exercises that you should go through and
solve on your own. The only way to learn Python is to do lots of Exercises!

Exercise 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 different 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 (fahrenheit.py):


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 − 3 2 ) ∗ ( 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 (testfahrenheit.py):


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 different self-paced Exercises that you should go through and
solve on your own. The only way to learn Python is to do lots of Exercises!

Exercise 8.2.1. Create Python Module for converting between radians and
degrees
Since most of the trigonometric functions require that the angle is expressed in
radians, we will create our own functions in order to convert between radians

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 different 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 different useful resources for File Handling.

Python File Handling - w3school:


https://www.w3schools.com/python/pythonf ileh andling.asp

Reading and Writing Files - python.org:


https://docs.python.org/3/tutorial/inputoutput.htmlreading-and-writing-files

9.6 Exercises
Below you find different self-paced Exercises that you should go through and
solve on your own. The only way to learn Python is to do lots of Exercises!

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
Table 9.1: Logged Data
Time Value
1 22
2 25
3 28
... ...

78
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 ”<ipython −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 ”<ipython −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 ”<ipython −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

You might also like