0% found this document useful (0 votes)
11 views24 pages

Laboratory Work 5

This document provides an introduction to Python syntax and the Jupyter Notebook development environment, emphasizing Python's versatility and its libraries for tasks such as data processing and machine learning. It outlines various Python development environments, including Jupyter Notebook and Google Colab, and explains basic operations, functions, comments, variables, and data types in Python. The document also includes instructions for creating a notebook in Google Colab and performing simple calculations.

Uploaded by

BEN MOSSES
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)
11 views24 pages

Laboratory Work 5

This document provides an introduction to Python syntax and the Jupyter Notebook development environment, emphasizing Python's versatility and its libraries for tasks such as data processing and machine learning. It outlines various Python development environments, including Jupyter Notebook and Google Colab, and explains basic operations, functions, comments, variables, and data types in Python. The document also includes instructions for creating a notebook in Google Colab and performing simple calculations.

Uploaded by

BEN MOSSES
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
You are on page 1/ 24

Basics of Python Syntax

Objective: Introduction to Jupyter Notebook - a development environment in


Python, learning the basics of language syntax and the main principles of computing.

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.

Python Development Environments


Since Python is an open-source product, anyone can create their own development
environment for it. At the same time, Python programs can be written even in a notepad
and run in the command line. Currently, there are a number of the most common
development environments in Python (all of the listed environments are distributed free
of charge, although some have additionally more functional paid versions):
● Python IDLE is a basic environment that comes with Python when you install it
on your computer. It has only the most necessary functions, so it is simple, but
limited in its capabilities.
● Jupyter Notebook is a web application-based development environment in
which the lab work of this course is supposed to be performed. It is easy to use
and can be used in the cloud, i.e. remotely. Like Google Docs, it allows for
shared access to a project and version control. Its functionality is inferior to the
most powerful environments, but for beginners and small projects, this
functionality is not required.
● Spyder is a development environment created specifically for Python, with a
focus on scientific computing. It allows you to conveniently work with code and
has tools for visualizing results.
● Visual Studio Code is a powerful development environment that supports a large
number of programming languages, including Python. It will be too complicated
for a beginner, but those who have experience using the environment for other
languages will find it convenient to use it for Python as well.
● PyCharm is a feature-rich development environment created specifically for
Python, so it is convenient in terms of code completion and inspection, error
highlighting and debugging. However, it is not recommended for beginners, as
it is somewhat more complex than IDLE, Spider and Jupyter. Notebook .
● General-purpose text editors with support for programming languages ( Subline
, Vim , Notepad++) - they are simpler and less functional than integrated
development environments.
Below examples are shown for Jupyter. Notebook , running in the Google Colab
system . Google Colab is a cloud environment that allows you to have remote access to
your projects. Also in the appendix to this work there is an instruction on how to install
Python locally on your computer and work with it (but this is not necessary for
completing the lab work of this course).

Interface Wednesday Jupyter Notebook in Google Colab


Google Colab is a cloud platform for creating and distributing solutions in the field
of data processing and visualization, machine learning, and simple programming in
Python. Firstly, Google Colab is convenient for the educational process because it does
not require installation and personalized settings on the computer, eliminating the need
to copy and transfer data. This allows the user to work on projects at any workplace
(computer) with an Internet connection. Secondly, Google Colab has a number of
advantages listed below that attract both beginners and professionals in mathematical
modeling and Data Science.
Work in Google Colab is built on the principle of the Jupyter notebook Notebook
. The essence of this principle is that the program code, explanations for it and the results
of the work are placed in one space, divided into cells ( cells ), an example is shown in
Figure 1. Such logic is especially convenient for programming in modeling tasks, data
analysis, scientific research, because everything is on one screen. While the classic
approach to creating software involves writing code in some files, documentation in
others, and to get the results of the work you need to run the created program.

Figure 1 – Example Jupyter notebook from jupyter.org

Create a notebook in Google Colab and use it for simple calculations

1. Getting started, simple calculations


1. Go to the Google Colab page at https://colab.research.google.com/ .
2. You need to sign in to your Google account, for this you may need to create
one: https://www.google.com/account/about/ .
3. From the main menu, select File, then New Notebook (Figure 2).
Figure 2 – Creating a new notebook

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 .

Figure 3 – Renaming a notebook

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.

Figure 4 – Empty cell for code

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

Figure 6 – Example of calculations with complex numbers

Basic arithmetic operations in Python:


● addition, + ;
● subtraction, - ;
● multiplication, * ;
● division, / ;
● getting the integer part of a division, / / ;
● obtaining the remainder from division, %;
● raising to a power, **.
The order of operations is the same as in mathematics and most programming
languages. For example, if you write 10 + 5 * 2, then first the multiplication 5 * 2 will
be performed, then the result will be added to 10.
8. Try to perform various calculations. You can use long expressions and brackets,
for example:

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

Figure 8 – Colab only outputs the results of the last row

Figure 9 – Outputting results using the print function

2. Packages, functions and advanced calculations

Functions in programming allow you to write a sequence of actions once, which


can then be used many times. A function usually has a name and input arguments.
Functions allow, firstly, to better structure the code by dividing it into separate simpler
blocks, and secondly, to significantly reduce the amount of code due to its reuse .
A package or library is a certain set of data and functions, united according to their
purpose. For example, it is logical to combine mathematical functions into one module,
functions for working with files into another, but it makes no sense to put trigonometric
functions together with file reading functions into one module.
Some Python functions are embedded in the language core, some are placed in the
standard libraries (packages) of the language. In addition, there are a huge number of
packages that are not included in the standard set, but are easily connected.
Most of Python's mathematical functions are in a package called math . You can
include the package like this:
import math
It is logical to place part of the code for connecting the package in a separate cell
and execute it once to connect the package to the project. There is no point in pasting
the code for connecting the library several times inside the notebook. And it would be
bad style to paste the connection in the middle of the notebook.
Next, to use functions from a package, you need to write the package name and
put a period before the function name. Moreover, after putting a period, the environment
itself will open a list of all functions of the package (Figure 10). If you start typing the
function name, the list will be updated in accordance with the characters entered.

Figure 10 – Autocompletion shows package functions

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:

print( m.fabs ( m.sin ( -0.1 )))

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.

Figure 12 – Text input block

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.

5. Data Types in Python

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.

6. Variable Naming Rules in Python

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 :

help ( ' keywords ' )


There are special naming guidelines, because program code with unclear or too
long names is very inconvenient to work with. Some recommendations:
● do not use meaningless names ( qwe , abcd , a111);
● do not use transliteration ( number , length , line );
● use only lowercase letters and numbers in variable names and separate parts with
underscores ( new_object , last_event , point_1);
● do not make names too long (more than 4 words);
● For variables that are used only in a small local area of code (up to ten lines),
you can give short names (1-3 characters) without a specific meaning (a, i, j, n,
tmp , …).

7. Example of calculations with variables

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

print( ' Searched allocated power = ' , p, ' W ' )

8. Using the print function to output results

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 ( 'Power output = {0:.4f} W' . format (p))


In this example, a block in curly braces is placed inside the string. The zero inside
the block means that the zero (leftmost) value passed to the format function (inside the
braces) should be placed there, then after the colon there are instructions on how exactly
to output the value. In this case, “.4f” means that the number should be output in floating
point format (“f” here means float ) with only four significant characters after the
decimal point.
Below are some more examples of using the format function .

print ( '{0} and {1}' . format ( 'A' , 'B' )) # Result: A and


B

print ( '{1}, {0}, {2} and {1} again' . format ( 'A' , 'B' ,
'B' ))
# Result: B and A, C and B again.

print ( 'The value of PI is approximately {0:.1f}.' . format


( 3.142 ))
# Result: The value of PI is approximately 3.1.

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

Figure 14 – Example of a syntax error due to an incorrect variable name

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)

NameError: name 'c' is not defined

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

x1 = (-b + m.sgrt (D))/( 2 *a)


x2 = (-b - m.sqrt (D))/( 2 *a)

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)

AttributeError : module 'math' has no attribute ' sgrt '

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

x1 = (-b + m.sqrt (D))/( 2 *a)


x2 = (-b - m.sqrt (D))/( 2 *a)

Message about error :


File "<ipython-input-11-b7e3157b898c>", line 4
D = b**2 - 4ac
^
SyntaxError : invalid syntax

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

x1 = (-b + m.sgrt (D))/( 2 *a


x2 = (-b - m.sqrt (D))/( 2 *a)

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 1 – Testing table


Result of the
Initial values Correct result Comparison
program
x1=1.7071,
a=2, b=-4, c=1 x1=1.7, x2=0.3 +
x2=0.2929
a=0, b=4, c=-1 x1= NaN , x2=- Inf x1=0.25 -

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

x1 = (-b + m.sgrt (D))/ 2 *a


x2 = (-b - m.sqrt (D))/ 2 *a
print( '{0:.4f} {1:.4f} ' .format (x1, x2))

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.

o Basic arithmetic operators must be used to calculate age.

o The result should be in the format: Your age this year: X.


Task 2: "Ideal Body Mass Index (BMI)"
Write a program that asks the user for their current weight in kilograms, height in
meters, and their current year and year of birth. The program should calculate the user's
body mass index (BMI) and age, and then print both results.
Formulas:
o Body mass index (BMI) is calculated using the formula: BMI = weight / (height
* height)
o Age is calculated as the difference between the current year and the year of birth.
Problem 3: "Area of a triangle
Write a program that reads the lengths of two legs entered from the keyboard in a
right triangle and outputs its area.

Problem 4: "Angle converter and calculation of sines and cosines"


Write a program that converts an angle from degrees to radians, and then
calculates the sine and cosines for that angle. The program should output results
accurate to three decimal places.
Requirements:
o The program should ask the user for an angle in degrees.
o Angles must be converted to radians before calculating sine and cosine.
o Results should be rounded to three decimal places.
Problem 5: Manhattan Distance
When walking around Manhattan, you can't take the shortest route from point A
to point B. Unless you can walk through walls, you'll have to walk along its parallel-
perpendicular streets.
On the plane, the Manhattan distance between two points ( p 1 ; p 2) and ( q 1; q
2) is defined as: ∣ p 1− q 1 ∣ + ∣ p 2− q 2 ∣ .
Write a program that determines the Manhattan distance between two points
whose coordinates you can enter into the program from the keyboard.
Appendix - Instructions for installing Python on a personal computer

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

Figure 16 – Installing Python on Windows (version 3.8 may vary)


As a result, Python and the basic development environment - IDLE will be
installed (it can be found in the list of programs or in the path that was specified during
installation, as, for example, in Figure 16). Instructions for working with IDLE can be
found on the Internet by searching for “IDLE instructions” or “IDLE quick start”.
For example, you can create a file with Python code on your computer using
IDLE, Notepad++ 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 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 ()

The my_app.py file can be double-clicked as you would normally do to launch


applications or open files, and a window will open as shown in Figure 18.

Figure 18 – A simple Python application with a graphical interface


But at the same time, the terminal (Windows command line) will open; to prevent
this from happening, you need to change the file extension from “ py ” to “ pyw ”.

Installing additional libraries


To install a library that is not part of the basic set of libraries (for example, NumPy
, which will be discussed later in the course), you need to use the pip command . To do
this, open a command window and enter
pip install <name> --user
Instead of < name > you need to specify the name of the library being installed,
for example:
pip install numpy -- user
Building portable executable applications
If the file with the code is .py or . pyw try to run on another computer that does
not have Python or the necessary libraries installed, it will not run. In addition, your
code will be open for viewing and editing. To ensure that your application is
independent and portable, as well as to provide minimal (and yes, minimal) protection
for your code, you can build an executable file (EXE), which will contain everything
you need.
There are various ways to do this, one of them is to use the PyInstaller library . It
needs to be installed:
pip install pyinstaller --user
And then run the following command from the folder containing the file with the
application code (if the application is divided into several files, then with the file
containing the code to start working):
pyinstaller <name> -F
For example :
pyinstaller my_app.pyw -F
dist folder will be created , containing the executable file my_app.exe. It can be
run on computers that do not have Python installed.

Linux using Ubuntu 20 as an example


Because of the large number of Linux distribution versions, it is best to find
instructions for your version of Linux. Below is an example for Ubuntu 20.

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)

Figure 19 – Running a Python script from the Linux 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 ()

Running this code from the terminal will create a window as shown in Figure 20.

Figure 20 – A simple Python application with a graphical interface


By default, Linux scripts do not run on double-click like Windows executables,
although this behavior can be changed in the settings. In addition, the file settings must
allow it to be executed as a program, and at the beginning of the Python code in the file
you will need to write
#!/ usr/bin/env python3
Installing additional libraries
To install a library that is not part of the basic set of libraries (for example, NumPy
, which will be discussed later in the course), you need to use the pip command . To do
this, open a command window and enter
pip install <name> --user
Instead of < name > you need to specify the name of the library being installed,
for example:
pip install numpy -- user

You may need to install the PIP tool itself first:


sudo apt install -y python3-pip
python3 -m pip install --upgrade pip

Building portable executable applications


py code on another computer that does not have Python or the necessary libraries
installed, it will not run. In addition, your code will be open for viewing and editing. To
ensure that your application is independent and portable, as well as to provide minimal
(and that is minimal) protection for your code, you can build an executable file that will
contain everything you need.
There are various ways to do this, one of them is to use the PyInstaller library . It
needs to be installed:
pip install pyinstaller --user
And then run the following command from the folder containing the file with the
application code (if the application is divided into several files, then with the file
containing the code to start working):
pyinstaller <name> -F
For example :
pyinstaller my_app.pyw -F
dist folder will be created , and it will contain the my_app executable file .

You might also like