Laboratory Work 5
Laboratory Work 5
Introduction
Python is a platform-independent, high-level, freely distributed programming
language that is widely used in many tasks, in particular data processing and
visualization, machine learning. Python, due to its simplicity and versatility, is used in
most modern courses on machine learning, in many courses on algorithms, optimization
methods, and applied mathematics in general. A feature of Python is the presence of a
huge number of open-source libraries written in this language, such as:
● NumPy is a library for matrix computations,
● Pandas is a library for working with tabular files, including formats such as
XLSX,
● SciPy is a library for scientific and engineering calculations,
● Scikit-learn - a library of machine learning algorithms,
● Pandapower - library for calculating electrical network modes.
In addition, you can find libraries for web development, creating telegram bots,
working with databases, image processing, creating and training artificial neural
networks, and much more.
One of the main advantages of Python is that the user only needs to know as much
about it as the task at hand requires, because power engineers are not required to have
deep knowledge of programming. If the task requires the use of any special tools, the
user is provided with a virtually universal programming language with a large number
of libraries. And in the simplest case, Python can be used as a calculator for simple
calculations, solving equations, or a means for visualizing data from table files.
Python allows you to solve many problems in the energy sector, from the simplest
calculations of electrical circuits to the development of new types of equipment and
modeling of energy systems. Together with the Pandapower library, you can model
various electrical circuits, conduct data analysis, and process the results obtained.
4. You will see a blank notebook, give it a name, for example, “ First_notebook ”
(Figure 3). To open a previously created notebook later, you need to go to the Google
Colab page and use the File → Open notebook menu .
5. The notepad consists of two types of cells: code and text. Under the main menu
are the “+Code” and “+Text” buttons for adding cells. When creating a new notepad, it
contains only one block for code (Figure 1.4). In Figure 4, the symbol “1” is the code
line number, it may not be there depending on the environment settings.
In this cell you can enter Python code. For example, to perform simple
calculations.
6. Enter the line:
10 + 5
7. Press Ctrl+Enter or the arrow on the left side of the block; the calculation result
will appear under the cell with the code (Figure 5).
Figure 5 – Calculation results
You can use Python as a calculator without programming skills. For example,
perform calculations with complex numbers (Figure 6).
( 10 + 5 * ( 4 - 3 / 2 )) ** -0.5
To delete a block, click on it and then on the trash can icon (Figure 7).
Figure 7 – Illustration of the block delete button
Google Colab automatically prints the results of only the last line (Figure 8). To
print intermediate results, you need to use the print function (Figure 8).
Typing the full package name is not very convenient. That's why Python has the
ability to give packages short aliases. This is done as follows:
import math as m
In this case, m becomes an alias for the math library , and after executing this code,
functions in the math package can be accessed by typing just “m.”, for example:
m.sin(m.pi/2)
In this example, sin is the sine function, and pi is a constant, the π constant. Its
value is stored in the math library , so to access it, you use the code m.pi . Similar to
how “ m.sin ” is used to access the sin function . The function name is always followed
by parentheses, in which the input arguments are placed, as in mathematical notation of
functions. Examples of various functions are shown in Figure 11.
Figure 11 – Examples of mathematical functions of the math package
print function has no output values, it prints text on the screen. Mathematical
functions return the result of calculations. For example, if you write:
10 + m.log10( 100 )
then the result of calculating the decimal logarithm of 100, equal to 2, will be added to
10, and the result will be 12.
The result of one function can be used as an argument to another, for example:
3. Comments
An important part of the program code are comments that explain its operation.
The skill of writing good comments, concise and clear, without redundancy and
ambiguity, comes with experience. The general principle is that comments should help
to use the code. The purpose of comments is not to describe everything that is done in
the code (this should be mostly clear from the code itself), but to give the reader of the
code the necessary hints. In this manual, comments in the code are usually more
detailed, since they serve as an explanation in the learning process.
There are two ways to format comments in Python.
1. A single-line comment begins with the # symbol and ends at the end of the line.
# just a comment
A multi-line comment begins and ends with three single quotes.
'''
first line second line'''
If you execute this code fragment, the comment itself will be output as a result.
Since in the runtime environment, the last action performed in a cell is always output as
a result. If the last thing in the cell is comments, then they will be output.
In addition to such text explanations, you can create more complex ones in the
notebook, containing formatting, images, tables and other elements. For this, use the
“Text” type blocks.
Add such a block to your notebook (adding blocks was illustrated in Figure 4),
you will see a panel for editing text with formatting, as shown in Figure 12.
Unlike the usual for most text editors, this one uses the principle of using special
designations (markup). Write in the “ text ” field, then click on the icon with the letter
B. The result is shown in Figure 13. Two asterisks appeared to the left and right of the
text – this is a conditional designation of the bold style. If you click on another cell, the
code will be hidden, leaving only the visual result.
Figure 13 – On the left in the cell is the code with conditional symbols for design, on
the right is the result
Google Colab uses a popular text markup language called Markdown (it can be
considered as a very simplified version of HTML).
4. Variables in Python
A variable in programming is usually a name-value pair. The value can be
something simple (an integer, a symbol, a real number) or as complex as you like (a
string, a vector, a matrix, a table, an image, a document, a function). This is a conceptual
concept, but in different programming languages, variables differ in the logic of their
implementation and use.
In Python, every variable is a pointer (or reference, for Python it's the same thing)
to some area in memory that contains data. Code
a = 100
creates a reference named a to a memory location with the value 100.
Let's look at some examples:
a = 100
b = a
a = 200
1. A reference named a is created to a cell with the value 100.
2. A reference named b is created , the same as a, that is, it also refers to the same
cell with the value 100.
3. The link a is redirected to the cell with the value 200.
Second example:
a = 1000
a = a + 100
First, a cell with the value 1000 will be created, which is referenced by the variable
a, then a cell with the value 100, then 1000 and 100 will be added together and the result
will be written to a new cell, which will ultimately be referenced by a.
The main (basic) data types in Python can be divided into simple and complex
(composite). Simple:
● integer ( int ): 1, -10, 52256, ...
● real number ( float ): 0.01, 1e-10, 999.99999, …
● boolean number ( boolean ): False, True.
● complex number ( complex ): 5 + 10j, -5.1 + 0.1j, ...
● string ( str ): "Hello", 'A', "This is a string!", …
Complex ones include lists ( list ), tuples ( tuple ), dictionaries ( dict ), sets ( set ),
and others. They will be discussed as needed in the following sections.
All simple types are immutable . This means that once a cell of this type is created,
its value cannot be changed. But as shown above, you can change a variable of this type
by redirecting it to another cell.
Variable names in Python can only consist of Latin letters, numbers, underscores,
and cannot start with a number: width , time_1, _ my_name _, Student , etc. In addition,
names cannot match language keywords such as if , while , def . A list of keywords can
be obtained using the help function :
Variables make even simple calculations more convenient, since they allow you
to store intermediate results in new variables. Below is an example (you can put it all in
a code block in Google Colab )
'''
Example of solving a physics problem on the released
powerGiven: Heating elements (with a resistance of r Ohm
each) are connected in series in n1 to n2 parallel branches.
The EMF of the source is e V, the internal resistance is re
Ohm.
Find the power released in the external circuit.
'''
# Input data:
r = 1 # Om
n1 = 5 # series connection
n2 = 3 # parallel connection
e = 15 # V
re = 0.5 # Om
# Solution:
r_sum = r * n1 / n2
i = e / ( r_sum + re)
p = ( i ** 2 ) * r
Python provides a lot of options for formatting the output of text results. The last
line of code in the example above calls the print function . But the result is not very
pretty, as it prints too many digits after the decimal separator.
You can change the print function call as follows.
print ( '{1}, {0}, {2} and {1} again' . format ( 'A' , 'B' ,
'B' ))
# Result: B and A, C and B again.
A function can be called by itself (like print ), with a package (like m.sin ), or it
can be called as a method of a variable (like format ). In the latter case, the function is
applied to the variable. Thus, the format function applied to a string, such as '{0} and
{1}', to make it into a new string according to the given formatting rules.
Testing programs
After writing a program, it must be checked for functionality and correct
execution. This process is called testing and is labor-intensive, but mandatory. Even if
the program runs and produces something, it is necessary to make sure that its
calculations are correct under all conditions. Programming errors are divided into two
types:
● syntactic - these are errors in writing commands in the programming language;
● Semantic errors are errors associated with an incorrectly composed algorithm
for solving a problem.
Syntax errors are easy to spot when you first run the program. A message about
the error will appear under the cell with the code. Examples of common errors are given
below.
1. Variable name
If you try to create a variable with an incorrect name, an error message will be
displayed (Figure 14):
2. No variable
A common mistake is to fail to assign a value to one or more variables before
using them in an expression. Consider an example of calculating the roots of a quadratic
equation that lacks an assignment to the variable 'c':
a = 2
b = -4
D = b** 2 - 4 *a*c
x1 = (-b + m.sqrt (D))/( 2 *a)
x2 = (-b - m.sqrt (D) )/( 2 *a)
When you try to run this calculation, the following message will appear:
NameError Traceback (most recent call last)
<ipython-input-2-0f379ac84ced> in <module >( )
1a=2
2 b = -4
----> 3 D = b**2 - 4*a*c
4
5 x1 = (-b + m.sqrt (D))/(2*a)
From the message you can see that the error is related to names ( NameError ),
that there is a space in the line D = b**2 - 4*a*c (the arrow points to it), and that the
error is that the name 'c' is undefined ( name 'c' is not defined ).
If you run the code locally instead of in the cloud, then instead of python-input-
2-0f379ac84ced, the file with the code containing the error will be specified.
3. Function name
It is also possible to make a mistake in writing the function name. Let's consider
again the example of calculating the roots of a quadratic equation, which uses the
function ' sqrt ' - calculating the square root. Let's write this function as ' sgrt '.
a = 2
b = -4
c = 1
D = b** 2 - 4 *a*c
Visually, this error is difficult to notice, but when you try to calculate, a message
will appear:
AttributeError Traceback (most recent call last)
<ipython-input-8-1d668e843f85> in <module >( )
4 D = b**2 - 4*a*c
----> 5 x1 = (-b + m.sgrt (D))/(2*a)
6 x2 = (-b - m.sqrt (D))/(2*a)
The message shows the line number and indicates that there is no function ' sgrt '
in the math (m) library . Rename the function to sqrt and the problem will go away.
4. Lack of operator
When starting out with Python, a common mistake is to miss the multiplication
operator between variable names.
a = 2
b = -4
c = 1
D = b** 2 - 4 ac
It tells you that a syntax error has occurred, and the specific location in the line is
indicated (the arrow in the form of the ^ symbol points to it).
5. Indentation in code
Note that Python does not use brackets or keywords like begin and end to format
blocks of code. Instead, Python uses indentation. Therefore, you cannot indent the
beginning of a line in Python. For example, if you enter the code:
print ( 10 + 10 )
print ( 5 + 5 )
and try to execute it, then an error message will be displayed: “ IndentationError :
unexpected indent ” - unexpected indent.
6. No brackets
When writing large expressions with a considerable number of arithmetic
operations, one of the brackets is omitted or forgotten to be closed. In our expression
for calculating square roots, we will remove one of the brackets.
a = 2
b = -4
c = 1
D = b** 2 - 4 *a*c
When calculating, a message like this will appear indicating the line and that a
syntax error has occurred.
7. Semantic errors
Finding semantic errors is more difficult. Errors of this kind are not immediately
noticeable. The program will perform the calculation and will not issue any messages,
but the calculations will be incorrect.
To identify these errors, testing should be carried out after all syntax errors have
been corrected. First, a testing plan and table should be made. It is necessary to clearly
understand what kind of errors may occur. The program should also be checked for limit
values, as well as input data values that are outside the permissible range. An example
of a testing table for a program for solving a quadratic equation is given in Table 1.
Table 2 shows that when a=0, the program performs the calculation, does not
generate errors, but the root values are incorrect. This error occurred because when
compiling the program algorithm, all possible initial data and ways to solve the given
problem were not considered. The algorithm should be rewritten and the program
debugged, and the calculation should be provided for under this condition.
Let's give another example of a semantic error in finding the roots of a quadratic
equation. In calculating the roots of the equation, we remove the brackets from the
denominator.
a = 2
b = -4
c = 1
D = b** 2 - 4 *a*c
When starting the calculation, the program will perform the calculation and the
values of the equation roots will be displayed. As noted above, the priority of arithmetic
operations in this case will be as follows:
1. (- b+sqrt (D))
2. /2
3. *a
The answer for a=2, b=-4, c=1 is x1=6.8284, x2=1.1716. From Table 2 it is clear
that this answer is incorrect, although the program does not display an error in the
command window.
Therefore, it is important to test the program to check the correspondence between
the correct (expected) answers and the real ones that the program produces. At the same
time, if the program has passed the test, this does not mean that it is error-free. It means
that it works correctly on the input data used in the tests. With other input data, errors
may be detected.
Methodological instructions
Task 1: "Age Calculator"
Write a program that asks the user for his current age and year of birth, then
calculates his age in the current year and prints the result.
Requirements:
o The program should ask the user for two values: the current year and his year of
birth.
To install Python on your computer, you can use the following instructions.
Windows
Installing Python
You need to download the distribution for installing Python and IDLE from the
website https://www.python.org/downloads/ (select the latest version under the
inscription “ Download the latest version for Windows”). Then run the downloaded
distribution. At one of the installation steps in the installer application window there
will be an option “ Add Python XX to PATH”, you need to tick it (Figure 16).
a = 10
b = 20
print ( a+b )
This script can now be run from the command line (Figure 17)
Figure 17 – Running a Python script from the Windows command line
Python can also create executable applications. The simplest example is given
below (the code should be placed in a separate file, for example, “my_app.py”):
import tkinter as tk
window = tk.Tk ()
greeting = tk.Label (text= "Hello, Tkinter " )
greeting.pack ()
window.mainloop ()
Installing Python
You can check if Python is installed by entering the command in the terminal
python3 --version
To update the version of Python, as well as other software in the system, you can
use the commands:
sudo apt-get update
sudo apt -y upgrade
The IDLE environment can be installed as follows:
sudo apt -y install idle3
This will install Python and the basic IDLE development environment. You can
find instructions on how to use IDLE online by searching for “IDLE instructions” or
“IDLE quick start”.
For example, you can create a file with Python code on your computer using IDLE
or another editor. For example, a file named script_sample.py with the following
contents:
a = 10
b = 20
print ( a+b )
This script can now be run from the command line (Figure 19)
Python can also create executable applications. The simplest example is given
below (the code should be placed in a separate file, for example, “my_app.py”):
import tkinter as tk
window = tk.Tk ()
greeting = tk.Label (text= "Hello, Tkinter " )
greeting.pack ()
window.mainloop ()
Running this code from the terminal will create a window as shown in Figure 20.