Python for microcontrollers. We learn to program single-board computers in a high-level language. Interaction with the board. Preparing for work

| -- [ Page 1 ] --

Chaplygin A. N.

Learning to program with Python (Start with Python) Revision: 170 Revision: 170 Contents Contents Contents......................... ........................................................ ........................................................ .....2 Preface................................................... ........................................................ ........................................... 5 Thanks....... ........................................................ ........................................................ ........................7 Introduction........................ ........................................................ ........................................................ ................. 8 z0.1. Basic knowledge................................................ ........................................................ ...................9 z0.2. Where can I get a Python interpreter?................................................. ...............................9 z0.3. Installing the Python interpreter on UNIX.................................................... ................ s0.3.1. Installing/updating Python from an rpm package.................................................... ............... s0.3.2. Installing Python from source code.................................................... ........................... s0.4. Installing Python on Windows.................................................... ........................................ s0.5. Running programs written in Python.................................................... ............................ s0.6. Development environment................................................ ........................................................ .............. Chapter 1. Basic concepts.................................... ........................................................ ............................ h1.1. Algorithms and programs................................................................... ........................................................ .. h1.2. Programming languages ​​and abstraction levels................................................................. ................ h1.3. Formal and natural languages................................................................. .................................... h1.4. Interpreters and compilers................................................................. ........................................ h1.5. First program................................................... ........................................................ ............. h1.6. What is debugging?................................... ........................................................ ........................... s1.6.1. Syntax errors.................................................................... ........................ h1.6.2. Runtime errors.................................................................... ............................... s1.6.3. Semantic errors.................................................................... ...................... h1.6.4. Debugging process................................................... ........................................................ ....... Chapter 2. Variables, operations and expressions.................................... ..................................... h2.1. Values ​​and types...................................................... ........................................................ ................. h2.2. Type Conversion................................................................ ........................................................ ...... h2.3. Variables........................................................ ........................................................ ........................... h2.4. Variable names and keywords................................................................. ................................. s2.5. Expressions........................................................ ........................................................ ........................ h2.6. Executing expressions................................................... ........................................................ ... z2.7. Operators and operands................................................................... ........................................................ ...... z2.8. Order of operations................................................... ........................................................ ............. h2.9. The simplest operations on strings.................................................... ................................. s2.10. Composition................................................. ........................................................ .....................Chapter 3. Functions.................................. ........................................................ ............................................... 3.1 . Subroutines........................................................ ........................................................ ................. h3.2. Function calls........................................................ ........................................................ ............... h3.3. Reference system................................................ ................ ............................................... h3.4. Importing modules and mathematical functions.................................................... .................... s3.5. Composition................................................. ........................................................ ........................... h3.6. Creating functions................................................ ........................................................ ............ h3.7. Parameters and arguments................................................... ........................................................ .... s3.8. Local variables........................................................ ........................................................ .... s3.9. Execution flow................................................... ........................................................ ............ h3.10. Stack diagrams......................................................... ........................................................ ...... s3.11. Functions that return results................................................................... ...................................Chapter 4. Computer graphics............ ........................................................ ................................... Revision: 170 Contents Chapter 5. Logical expressions, conditions and recursion... ........................................................ ...... h5.1. Comments in programs................................................... ................................................... s5. 2. Simple Boolean Expressions and Boolean Data Type.................................................... h5.3. Logical operators................................................... ........................................................ ..... h5.4. Execution by condition and emptiness.................................................... ................................. s5.5. Entering data from the keyboard.................................................... ........................................................ h5.6. Alternative program branches (Chained conditionals)................................................... ... з5.7. Empty blocks................................................... ........................................................ .................... s5.8. Nested conditional statements(Nested conditionals)................................................... ..... s5.9. Recursion......................................................... ........................................................ ............................ s5.10. Stack diagrams of recursive calls.................................................................... .................... h5.11. Maximum recursion depth................................................................... .................................... h5.12. Fibonacci numbers................................................... ........................................................ ............ Chapter 6. Cycles.................................... ........................................................ ........................................... h6.1. Operator while loop ........................................................ ........................................................ ..... h6.2. Counters........................................................ ........................................................ ........................... h6.3. Endless loops................................................... ........................................................ .......... h6.4. Alternative branch of the while loop.................................................... .................................... s6.5. Tabulation of functions................................................... ........................................................ .. h6.6. Special and escaped characters.................................................................... ............................... s6.7. Fibonacci numbers and the while loop operator.................................................... ........................... s6.8. Nested loop statements and two-dimensional tables.................................................... .......... z6.9. Classification of loop operators.................................................................. .................................... s6.10. Control structures................................................... ...................................................Chapter 7. Lines................................................... ........................................................ ............................... h7.1. Indexing operator................................................... ............................................. з7 .2. String length and negative indices................................................................. ............................... h7.3. Enumeration and for loop................................................... ........................................................ ............... s7.4. Line cuts........................................................ ........................................................ ....................... s7.5. String comparison................................................... ........................................................ ................ s7.6. Lines cannot be changed................................................... ........................................................ .... з7.7. find function................................................... ........................................................ .................... s7.8. Loops and counters................................................................... ........................................................ ............... s7.9. String module......................................................... ........................................................ ............................... s7.10. Classification of symbols................................................... ................................................... s7. eleven. Unicode strings................................................... ........................................................ ................ Chapter 8. Lists................................... ........................................................ ............................................... h8.1. Creating lists........................................................ ........................................................ ............... s8.2. Accessing list items............................................................. ........................................................ h8.3. List length........................................................ ........................................................ .................... s8.4. Belonging to the list................................................... ........................................................ ... z8.5. Lists and for loop................................................... ........................................................ ............... s8.6. Operations on lists................................................................... ........................................................ .... з8.7. List slices........................................................ ........................................................ ................... s8.8. Changing lists........................................................ ........................................................ .......... z8.9. Deleting list items................................................................... ................................................... s8. 10. Objects and values........................................................ ........................................................ ......... z8.11. Links to objects........................................................ ........................................................ .......... z8.12. Copying lists........................................................ ........................................................ ..... Revision: 170 Contents h8.13. Parameter lists............................................................. ........................................................ .......... z8.14. Nested lists........................................................ ........................................................ .......... z8.15. Matrices........................................................ ........................................................ ......................... s8.16. Lists and strings................................................................... ........................................................ ............... Chapter 9. Tuples................................... ........................................................ ........................................... Chapter 10. Dictionaries... ........................................................ ........................................................ ................... h10.1. Creating a dictionary................................................... ........................................................ ............ h10.2. Operations on dictionaries................................................................... ........................................................ h10.3. Dictionary methods......................................................... ........................................................ ............ h10.4. Using aliases and copying.................................................... ................... h10.5. Sparse matrices................................................... ........................................................ .... h10.6. Hints........................................................ ........................................................ ....................... h10.7. Type long integer................................................................. ............................................... з10.8 . Counting letters................................................... ........................................................ ...................Chapter 11. Files and exception handling................................. ........................................................ ..... Chapter 12. Classes and objects.................................................. ........................................................ ............ Chapter 13. Classes and functions................................ ........................................................ ...........................Chapter 14. Methods.................... ........................................................ ........................................................ ... Chapter 15. Object Sets.................................................. ........................................................ .............. Chapter 16. Inheritance.................................. ........................................................ ...........................Chapter 17. Linked Lists.................. ........................................................ ............................................Chapter 18. Stacks... ........................................................ ..... ........................................................ ...................Chapter 19. Queues and priority queues............................ ...................................................Chapter 20 . Trees................................................ ........................................................ .......................Chapter 21. Functional Programming.................................. ............................................... Conclusion. Bird's-eye.............................................. ................................... Appendix A. Tips for debugging programs........ ........................................................ .............. Appendix B. Creating and using modules.................................. ................................ Appendix C. Creating Data Types............ ........................................................ .................... Appendix D. Writing GUI Programs.................................. ..........Appendix E. Team Development Methodologies.................................. .......................... Appendix F. Guidelines for teachers.................. ................................ Revision: 170 Preface Preface It all started with the fact that in the summer of 2002 I was completely disappointed V php language, on which I wrote quite a lot at that time. I specialized in web programming, so the choice of tool was generally logical, but when developing major projects php showed itself far from its best side: the lack of cascading exception handling tools, multiple inheritance and namespaces affected it.

In short, php did not suit me both for practical reasons and from an ideological point of view. As they say, nothing limits a programmer’s flight of thought more than a compiler/interpreter.

I started looking for an alternative to php. Before php, I had to work with the perl language, which did not suit me for the same reasons. C++ is also not the most convenient language for developing web applications, because... The cost of owning such applications is quite high. And so I came across Python (Python, the idea of ​​using Python was picked up by Dmitry Brechalov, my friend, with whom we corresponded very productively and exchanged books. He quickly mastered Python and managed to write in it even for his Psion handheld. He also sent me email a link to the project website How to think like a computer scientist. Learning with Python (I read the book in one sitting, I was struck by the way the material was presented. For example, the concept of recursion in this book is introduced before syntactic constructs that implement loops, and it is very clear and elegant. In school programs. recursive algorithms are usually included in the category of Olympiad problems.

The final impetus was when I started teaching computer courses at the Intellect Club foundation for children aged 9 to 13 years. Experiments with Pascal were unsatisfactory because... I had to be distracted by the intricacies of type implementation and various limitations inherent in this language, distracting from the essence of programming.

I didn’t even try to use C++, because... it's even more complicated. Python came to the rescue again.

I would like to thank executive director foundation, Andrei Repyakh, which gave me complete freedom, encouraging my experiments.

To be sure that I didn’t miss anything, I tried another language - Ruby (project website, but soon returned to Python. Ruby, like perl, is replete with constructs that only gurus can read, which does not help novice programmers at all. And In terms of the number of modules, Python is still superior to it.

So that children could study independently, I decided to translate the book How to think like a computer scientist. But during the translation process, I constantly had the desire to supplement it with my own ideas, to rearrange the chapters so that the presentation of the material was more logical. Moreover, I discovered many controversial issues. I ended up writing my own book, based on How to think like a computer scientist, but with additions and revisions. We can say that this is a Russian-language edition or a branch of the project.

The book turned out to be a little more complicated than planned: in general, it corresponds to the level of high school and initial courses Universities, but also junior high school students, with the support of the teacher, will also be able to master the material in the book without much difficulty.

This book is distributed under the OPL license (with restriction VI-B). This means that the text in this book can be freely used for any purpose, except for commercial ones.

Revision: 170 Preface Of course, non-commercial copies must be distributed with a license and without changing the authorship of the book. Otherwise, you are given complete freedom. Take it. Use it.

:) Revision: 170 Acknowledgments Acknowledgments This book is distributed as freely as word of mouth. Therefore, it is also freely developed, without restrictions by any licenses other than OPL. This book is due in large part to the contributions of the people listed here:

X Shlyakov Dmitry X Rudskikh Vyacheslav X Voloshin Evgeniy X Belchenko Alexander X Brechalov Dmitry X Otkidach Denis X Olishchuk Andrey X Churanov Mikhail X Pushilin Sergey X Litvinova Elena X Lipanin Anton X Zhukov Boris Many thanks to the enthusiasts of the free movement software(living all over the world, for what they do.

Special thanks to the project team of the open office suite OpenOffice.org (for the good product in which this book was written.

Revision: 170 Introduction Introduction At school, the teacher asks the students what their parents do. The girl reaches out her hand:

My dad is a doctor.

This is a good profession,” says the teacher.

“And my dad is a driver,” one of the boys boasts.

What an interesting profession. What does your dad do? - the teacher asks Vovochka, to which he calmly replies:

He plays the piano in a brothel.

The teacher is shocked;

that same day she goes to Vovochka’s house and indignantly says to her father:

How can you raise a child in such conditions?! Do you really play the piano in a brothel?!

Vovochka's dad is embarrassed:

You see, I'm a programmer. I specialize in TCP/IP networks, write distributed network applications for UNIX operating systems, but how can I explain this to a seven-year-old boy?

From the outside, the profession of a programmer (or any other computer specialist) perhaps looks somewhat mysterious. What are these people doing? They sit at the computer all day and tell each other strange jokes - until recently this was the way most people thought. But today, information technologies have penetrated almost all areas of human activity: from such familiar things as mobile phones to space technologies. Computers simplify working with documents and help optimize business processes. Thanks to inconspicuous people sitting at the computer all night long, we can communicate in real time with friends and business partners located anywhere in the world using the Internet. Zen Buddhists say: The work of the master is not visible.

This book aims to teach you not just how to write programs, but also how to think like a computer specialist. This way of thinking combines approaches used in mathematics, science, and engineering. Like mathematicians, computer scientists use formal languages ​​to record ideas, algorithms, and operations on specific objects. Like engineers, they design objects by assembling various components into systems and choosing solutions from possible alternatives. Like natural scientists, they study behavior complex systems, build hypotheses, conduct experiments.

The single most important skill of a computer specialist is the ability to solve problems. This skill involves the ability to formulate them, think creatively about possible solutions, and clearly communicate the chosen option. As it turns out, learning to program is a great opportunity to develop all these skills.

So let's get started. A detailed description of the process of installing the Python interpreter and everything you need to work with the book can be read in the next section.

Revision: 170 Introduction It is recommended that you familiarize yourself with it before moving on to studying the first chapter, so that you do not have any problems in the process of mastering the material in the book. But do not forget that the main thing is the desire to learn, the ability to ask questions and look for answers to them.

z0.1. Basic knowledge In order to master the material in this book, you will need basic computer skills, namely:

X Working with files and folders (directories);

X Launch programs;

X Editing text files;

X If you have a UNIX system installed on your computer, it will be very useful to be able to work in the console;

X Working on the Internet - you can find a lot of useful information there;

X At least a basic knowledge of English will be very useful.

Keep in mind that office packages (MS Office, OpenOffice.org, StarOffice and the like) will not help you with programming. Programs are typed in simple text editors such as MS Notepad (aka Notepad).

It’s good if you know what binary code is and know how to convert numbers from one number system to another, all this is usually taught in school computer science courses.

It doesn’t matter what operating system is installed on your computer - Python has implementations for all the most common platforms: Windows, UNIX (GNU/Linux, FreeBSD, etc.) and even Mac OS X. Moreover, programs written in the same operating system , will be successfully executed in any other if there is a Python interpreter installed!

Python is included with most GNU/Linux distributions, but this is not necessarily the latest version. Therefore, you should still look at the Python page and read the news. Python, like most community projects open source, is developing very dynamically. We strongly recommend using the Python interpreter version 2.3.3 or higher - this release corrected errors that made it difficult to write non-English programs.

Now let's take a closer look at the process of installing the Python interpreter on various operating systems.

z0.2. Where can I get a Python interpreter?

The Python language interpreter is freely distributed under the Python Software Foundation (PSF) License (which, in some ways, is even more democratic than the GNU GPL (GNU General Public License:

The official website of the Python language project is located at the address. Here in the Downloads section you can download the latest version for your operating system. For UNIX-like systems The interpreter distribution is available in two versions: in source code (archive.tar.gz), as an rpm package (.rpm, .src.rpm, compiled for your distribution) or a .deb package (for the Debian Linux distribution). For Windows OS, download the exe file, which contains the interpreter itself and the installation program.

Revision: 170 Introduction z0.3. Installing the Python language interpreter on UNIX In all UNIX-like operating systems (any BSD systems, GNU/Linux, Solaris, etc.), the installation process will be generally the same. In GNU/Linux distributions that support the RPM package management system, in addition to the standard UNIX installation process from source code, you can install Python from an rpm package. Moreover, in RPM-based GNU/Linux distributions (RedHat Linux, Mandrake, SuSE Linux, ASPLinux, ALTLinux) it is recommended to install Python from rpm.

Download the Python distribution and install it accordingly. To do this, you will need superuser rights (root). If you do not have a superuser password, then, obviously, you should ask the system administrator servicing your computer for help.

z0.3.1. Installing/updating Python from an rpm package If you are logged in as an unprivileged user, then switch to superuser mode:

# Then go to the folder where the rpm package is located and type the command (taking into account which version of Python you downloaded):

# rpm -i python-x.x.rpm z0.3.2. Installing Python from source code Unpack the source code from the downloaded archive:

$ gzip -cd python-x.x.tar.gz | tar xvf Go to the folder where the distribution was extracted and run the command:

$./configure Then you should start the Python build process:

$ make After it is completed, you need to switch to superuser mode and run the make install command:

# make install Actually, there are no differences here from the standard installation from source code for UNIX-like operating systems. On most systems, it is recommended to build the software in the /usr/local/src/ folder.

Revision: 170 Introduction z0.4. Installing Python on the OS Windows Installation Python on Windows is simpler than on UNIX. Just download the installation file (for example, Python-2.3.3.exe), run it on your machine and answer all the questions in the installation program, completing the answer by clicking Next.

First you need to specify where the interpreter should be installed. By default, it is placed in the C:\PythonXX directory, where XX is the version number. At this step, just click the Next button.

If you are installing Python for the first time, then check the No, do not make backups option.

The next step is to select the components to install. It is better to enable the installation of everything that is offered (including documentation). The complete set takes up about 20 megabytes on your hard drive.

Finally, you need to set a group name for the main menu. You can simply click Next The program will show summary information about what will be installed and where. Click Next again and wait for the installation to complete. Click Finish to exit the installer.

z0.5. Running programs written in Python In order to run a program written in Python, on UNIX systems you need to call the Python interpreter and pass it as a parameter the name of the file in which the program to be launched is located:

$ python my_program.py In addition, on UNIX operating systems, it is possible for a program to specify which interpreter should be called to execute it. To do this, in the first line of the program you can write:

#! /usr/bin/env python Then you need to make the file with the script executable:

$ chmod u+x my_program.py After this, the script can be executed by simply typing its name on the command line:

$ my_program.py or, if the first option doesn't work:

$./my_program.py Character sequence #! programmers usually read it as she-bang!.

In OS Windows programs written in Python are launched in the usual way - use Explorer to find the file containing the program and double-click on its icon with the left mouse button. Python, when installed, associates the .py file extension with the Python interpreter, so double-clicking on such a file will launch Python, which will execute the program written in the file. If your program does not have a graphical interface, the Windows operating system will open a console window. After finishing the program, this window will be immediately closed, so you may not have time to see the result of its work. You can avoid this by adding the following line at the end of the program:

raw_input("Press any key to exit") This will force the interpreter to wait for any key to be pressed before exiting the program.

If you specified another extension, the double-click launch method will not work. On Windows, Python programs must always have the extension .py or .

pyw. The second option differs in that Python starts silently, that is, without opening a console window. The .pyw extension is recommended for programs that have a graphical interface and do not require a console window at all.

Another option is to open an MS-DOS session window (or run FAR) and run the following command:

C:\Examples> python my_program.py With this command we launch the Python interpreter and tell it the program from which file it should execute.

z0.6. Development environment The standard Python package includes the integrated development environment IDLE, in which editing programs will be much more convenient than in a simple text editor. IDLE is written in Python using the platform-independent Tcl library, so it can easily run on any operating system for which a Python implementation exists. IDLE also has a built-in debugging system that allows you to run the program line by line, which makes it easier to find errors. If for some reason IDLE does not suit you, you can try other development environments.

UNIX systems have many editors that have their own advantages and disadvantages, both console editors (vi, emacs, built-in mc editor) and graphical ones (vim, emacs, kate, IDLE editor, etc.).

The easiest choice may be Kate - it is included with the latest versions of the KDE windowing environment. Kate can highlight program syntax, has a built-in console emulator and a special module that makes it easier to work with programs written in Python: a code browser, which is enabled through the Settings menu in the Application Modules section.

Another interesting editor: SciTE (In addition to highlighting, it can collapse blocks of text, which greatly facilitates the work when working with large programs, but does not have a code browser (at least in the standard package), in addition, SciTE still needs to be Russified, which can cause some difficulties for beginners.

For Python programming on Windows, there are also several good editors and environments other than IDLE.

Firstly, this is PythonWin - a very good Python development environment for Windows (it can be downloaded from the website PythonWin is distinguished by the absence of problems with Russian characters, a convenient programming environment and integration with the operating system.

Revision: 170 Introduction We can also recommend the UniRed editor (you can download it from the site. This is an excellent text editor for Windows 95/98/NT/2000/XP, which understands both Python syntax and all possible encodings (including all Cyrillic and all encodings of the Unicode family).

Finally, it is very useful for developing and running programs file manager FAR. Anyone who has worked with Norton or Volkov Commander will be well versed in FAR.

The built-in editor understands both Russian encodings used in Windows, and the manager itself is much more convenient for running console programs than a standard DOS window. On Windows OS, FAR is perhaps the most suitable environment for running Python programs.

Now we are fully armed and ready to start learning programming in Python. Let's move on to the next chapter, which covers the basic concepts.

Revision: 170 Basic concepts Chapter 1. Basic concepts First, you will have to understand some basic concepts. There is no need to memorize them - it is enough to understand them at least on an intuitive level. Later you will begin to use them in practice, and everything will fall into place. This is perhaps one of the most tedious parts of the book.

h1.1. Algorithms and programs The concept of an algorithm is one of the central concepts of the entire computer discipline. The word algorithm, in essence, is synonymous with the words method or recipe. We can talk, in this sense, about an algorithm for finding the roots of an equation from its coefficients, or about an algorithm for decomposing natural number into prime factors. If the algorithms are based on simple calculations, then such algorithms are called numerical. However, non-numerical algorithms are also considered quite often. For example, sequences of symbols: texts, formulas, etc. can act as source data and results. The role of operations is not the usual operations of addition, multiplication and the like, but operations of string concatenation or operations of replacing some characters with others according to some correspondence table. An example is encoding text in Morse code. There are algorithms for constructing complex graphic objects and converting them. In order to teach a computer to do something, you must first create an algorithm.

An algorithm is a method described in all details for obtaining results that satisfy the set conditions based on the initial data.

A program is a sequence of machine instructions that describes an algorithm.

Of course, in order to write a program, you need to come up with an algorithm.

Computer programs are usually written in special programming languages.

h1.2. Programming languages ​​and levels of abstraction There are several approaches to programming. Initially, calculations were described at the level of machine instructions in binary code. Logic similar programs was quite difficult to grasp due to the fact that the programmer had to pay attention to such issues as, for example, how many memory locations should be allocated to store a particular value. To add two numbers, it was necessary to first calculate the addresses of the memory cells in which the added values ​​were stored, and only after that perform the addition operation binary numbers. This approach to programming is sometimes called address-based.

It was very difficult to read and understand how a program written in binary code worked, let alone find and fix a bug in it. Therefore, to simplify their work, programmers came up with mnemonic codes (from the Greek Mnemonikos mnemon - remember) or mnemonics - letter designations of binary machine instructions that are easier to remember than sequences of zeros and ones. To simplify working with memory cells, the concept of a variable began to be used.

A variable - in programming, is a letter designation of a memory area in which a certain value is stored.

Revision: 170 Basic concepts To translate mnemonic codes into machine instructions and variable names into addresses of memory cells, a special program was used - a translator. Mnemonic code languages ​​are called assemblers.

Development technologies continued to develop, specialists looked for new approaches, and soon ideas began to crystallize, which later formed the basis of the so-called structural approach. It was noticed that all calculations are reduced to the following elementary actions:

X Entering data from the keyboard, from a file or from any device;

X Output data to the screen, to a file, to a printer or other device;

X Perform some operations on numbers, strings or other objects;

X Selecting a branch of program execution based on the decision made (for example, based on the results of comparing two values);

X Repeating a group of operations, most often with changing one or more parameters.

You will soon see that this is indeed the case. At the same time, new translators began to appear that converted programs written in languages ​​based on these basic operations into machine instructions. Such languages ​​began to be called structural or languages high level. Programs for high-level languages describe the computational process at a higher level of abstraction, i.e. allow the programmer to abstract from the features of the machine implementation.

Let's illustrate this with two simple examples. The first program imitates a low-level language, and the second one imitates a high-level one:

1. Enter the address of the first number into the edx register Enter into the counter register Enter into the eax register Label lp:

Compare the value of the eax register with the value stored at the address taken from the edx register. If it is less than or equal, then go to the l_next label. Write into the eax register the value from the cell whose address is stored in edx. The l_next label:

Add to the value of the edx register If the counter register is not 0, then decrease the value in the counter register by 1 and go to the lp label Write the value from the eax register to the Max variable 2. Write to the Max variable Repeat until the i variable changes from 1 to 10 s step +1:

If the i-th number is greater than Max, then put it in the Max variable. Output the value of the Max variable.

Revision: 170 Basic concepts Both programs find the maximum of ten given natural numbers.

The names of the operations have been changed to their Russian-language counterparts (this writing method is sometimes called pseudocode), but the meaning of the actions has been preserved, so it is not difficult to understand their difference.

Most often, programs written in high-level languages ​​work slower, because... translators do not build the most optimal machine code according to the program text. But high-level languages ​​have many advantages: they are easier to read and understand, and they are also portable. This means that high-level programs can run on different types of computers or operating systems with little or no modification, while low-level programs are usually written for a specific type of computer or operating system, and to port such programs they have to be rewritten to another platform.

Please note that in the first program the result is not printed. Withdrawal method low level program will vary depending on the platform on which it will be executed this program. Moreover, this program will also not be able to work on an Intel 80286 processor, because the edx and eax registers appeared only in the Intel 80386.

The classic structured languages ​​are C1 and Pascal. They allow you to describe computational processes at a higher level of abstraction than assemblers, but, nevertheless, they have a number of disadvantages. In particular, a programmer writing in these languages ​​still has to explicitly specify the type of variables with which his programs will work, so that the translator knows how much memory to allocate for storing them.

In addition, it is impossible to store, for example, a string in variables designed to store integers.

Recently, so-called very high-level languages ​​have begun to gain popularity. They allow you to abstract from variable types, which opens up new possibilities. We will get to know them as we study. Python language, which is one of the representatives of this group of programming languages.

h1.3. Formal and natural languages ​​Let's figure out how programming languages ​​differ from ours native language, which we have been speaking since childhood. There are two types of languages: natural and formal.

Natural languages ​​include the languages ​​spoken by people: Russian, English, French, Arabic and others. Most likely, they arose naturally when in ancient times people tried to explain something to each other. They are all quite complex, although we often simply do not notice it. In order to simplify the learning of foreign languages, people have come up with rules and dictionaries in which words from one language are given equivalents from other languages. Sanskrit is considered the most complex natural language: the first collection of Sanskrit rules (Panini's grammar, called the Octateuch, 4th century BC) contained more than 4,000 grammatical rules. Sanskrit has cases, 3 numbers in names, several hundred verbal and verbal forms, and there are means for the free formation of numerous derivative words. In addition, in Sanskrit you can find up to several dozen words symbolizing the same object, but reflecting different shades of meaning, so its expressive capabilities most often exceed average needs.

1 Read as si.

Revision: 170 Basic concepts One of the most simple languages The language you can speak is Esperanto.

Esperanto was invented by ophthalmologist Lazar (Ludovik) Markovich Zamenhof in the 19th century.

Already as a child, Zamenhof had the idea that one common language would help peoples better understand and respect each other more.

Zamenhof had excellent abilities for languages, and while still a schoolboy, in addition to his native Russian, Polish and Yiddish, he studied German, French, English, Latin, Ancient Greek, Hebrew - about fourteen languages ​​in total. He soon became convinced that neither ancient nor modern languages ​​were suitable as common languages. Then he decided to create new language, which would not belong to any one nation, would be easy to learn, but at the same time would not be inferior to national languages ​​in flexibility and expressiveness. And he succeeded - the entire grammar of Esperanto (together with phonetic rules) fits on two printed pages, all the words are international, and in terms of expressiveness Esperanto is not inferior (and in some ways even superior) to Russian. Esperanto estas tre interesa kaj esprima lingvo.

Can Esperanto be called a natural language? I think no. Despite the fact that it lives its own life and develops naturally, the grammar of Esperanto is still strictly formalized. Therefore, it rather refers to formal languages.

Formal languages ​​are languages ​​invented by people to solve specific problems. For example, a set of special symbols and rules for writing formulas used by mathematicians to write formulas and prove theorems is a formal language.

Chemists also use their formal language to write down the chemical structure of substances. Programming languages ​​are formal languages ​​designed to describe algorithms.

Formal languages ​​are characterized by having clear syntactic rules.

For example, 3+3=6 is a syntactically correct mathematical notation, but 3=+6$ is not. H2O is a syntactically correct chemical formula for a substance, but 2Zz is not.

When you read a sentence in Russian or an expression in a formal language, you determine its structure, often unconsciously. This process is called syntactic analysis or parsing. The equivalent English term is parsing.

For example, when you read the phrase Mom washed the frame, you use the spaces to determine the beginning and end of the words and only after that find the subject (lmama) and predicate (lmyla). Having analyzed the syntactic structure, you can understand its meaning - semantics.

Before converting a program into a form understandable for a computer, any translator performs syntactic analysis. During syntactic analysis, the translator parses the syntactic structure of expressions and finds so-called symbols (tokens) - syntactically indivisible parts. In this context, symbols can be names of variables, numbers, operation signs, keywords, and designations of chemical elements.

Using the $ symbol in the formula 3=+6$ doesn't make sense, which is one of the reasons why it's not mathematically correct. The same problem exists in the chemical formula Zz: there is no element in the periodic table with the designation Zz.

The second type of syntax errors is associated with incorrect expression structure, i.e.

sequence of characters. The expression 3=+6$ has an incorrect structure, because An addition sign cannot immediately follow the equal sign. Likewise, molecular formulas use subscripts, but they cannot precede the chemical element.

Revision: 170 Basic concepts Although formal and natural languages ​​have much in common, they have a number of important differences:

1. Unambiguity Natural languages ​​have many idioms and metaphors;

Often people determine the meaning of phrases depending on the situation in which they are used. Formal languages ​​are designed to ensure that expressions are not ambiguous. This means that an expression must have only one meaning, regardless of context.

2. Redundancy In order to get rid of ambiguity and avoid misunderstandings, natural languages ​​use redundancy: definitions and additions.

Formal languages ​​are concise and maximally expressive.

Most people accustomed to natural languages ​​usually have difficulty getting used to formal languages ​​(including programs). But it is worth remembering that the density of meaning in such languages ​​is greater, so they are slower to read and understand. Structure is very important in formal languages, so reading from right to left or bottom to top is not the best way to understand them. And finally, the little things matter. Small spelling and punctuation errors (and typos too), which can be ignored in natural languages, will have a big impact in formal languages, even changing the meaning to the opposite.

In mathematics there is an entire section devoted to the theory of formal languages. It is on the mathematical apparatus of this theory that the parser analyzers of translators are based.

h1.4. Interpreters and compilers There are two types of translators that convert program source code into machine instructions: interpreters and compilers. The interpreter reads a high-level program (or source code) and interacts directly with the operating system to execute it. The conversion and execution of the program is done line by line.

Result Source Operating Interpreter execution code program system Unlike interpreters, compilers completely convert the source code of the program into machine code (or so-called object code), which the operating system can execute on its own. This allows compiled programs to run even on computers that do not have a compiler.

In addition, such programs run faster due to the fact that the computer does not have to parse and convert it into a form that it understands every time before starting the program.

Object Result Initial Operational Compiler (executable) execution code system program code However, modern interpreters are also capable of storing intermediate code, the execution of which takes less time due to savings on parsing the source code. However, such intermediate code is understandable Revision: 170 Basic Concepts only to the interpreter, so to run the program it is still necessary to have it on the computer.

It must be said that with modern computer power and memory capacity, the difference in the speed of program execution between interpreters and compilers is almost unnoticeable, but the process of developing and debugging programs in interpreted languages ​​is much simpler2.

The Python language is interpreted because... programs written on it are executed by an interpreter.

There is an interesting project for the Windows version of Python: py2exe, which allows you to create independent exe files from scripts.

In fact, py2exe is not a compiler itself - it converts the script into intermediate code using Python itself and places the necessary part of the interpreter into the executable file, along with this intermediate code and the code of all modules used in the program.

So you get an exe file and one or more dll files containing your program along with the runtime environment. Now you don't need a separate Python interpreter to run this program.

However, the resulting executable file can only run under the Windows operating system. If your program is intended to run only on that system and you don't want to require users to install Python, then py2exe can be a very useful tool.

Get Additional information and you can download py2exe here:

z1.5. First Program It's time to launch the Python interpreter and write the first program.

There are two ways to use the interpreter: command mode and executing programs from files. If you type a command on the command line of the Python interpreter, the interpreter will immediately display the result of its execution:

$ python Python 2.3+ (#1, Sep 23 2003, 23:07:16) on linux Type "help", "copyright", "credits" or "license" for more information.

>>> print "Hello world!" Hello world!

The first line of the example is a command that starts the Python interpreter on the UNIX operating system. In the Windows operating system, to call the interpreter, simply call the IDLE development environment in the Start Programs menu. The next two lines are information from the interpreter (version number, copyright - so 2 Compiled languages ​​are still indispensable in real-time systems, in which even the slightest delay can lead to disaster (for example, such systems are used to control spacecraft maneuvers and the flow of complex physical processes in laboratory and production conditions).

Revision: 170 Basic concepts presented). The fourth begins with the interpreter prompt >>>, which indicates that it is ready to execute commands. We typed the command print "Hello world!", i.e. were instructed to display the line "Hello world!" on the screen, and next line the interpreter output what we asked for.

We can also write the program to a file and use an interpreter to execute it. Such a file is called a script or script (from the English script - script). For example, using a text editor, create a file prog1.py with the following content:

print "Hello world!" It is customary to end the names of files containing Python programs with the sequence of symbols .py (those who work in operating systems DOS systems or Windows will call it an extension). In order to execute the program, we must pass the name of the script to the interpreter as a parameter:

$ python prog1.py Hello world!

In other software environments, the method for starting programs may be different, but the principle of calling the interpreter will remain the same.

Exercise. Try changing your first program so that it contains syntax errors: first an error associated with an unrecognized syntax unit (i.e., an unknown word), and then an error associated with incorrect program structure (you can try swapping syntax units).

Experiment.

h1.6. What is debugging?

Programming is a rather complex process, and it is quite natural for a programmer to make a mistake. It so happened that software errors called bugs (from the English bug - bug). You won’t find this word in Russian-language literature, but in programmer slang it is used quite often along with the word glitch. The process of finding and eliminating errors in the English literature is usually referred to as debugging, but we will call it debugging.

There are three types of errors that can occur in programs:

syntax errors, runtime errors, and semantic errors. To find and fix them faster, it makes sense to learn to distinguish between them.

h1.6.1. Syntax errors Any interpreter will be able to execute a program only if the program is syntactically correct. Accordingly, the compiler will also not be able to convert the program into machine instructions if the program contains syntax errors. When the translator finds an error (that is, it comes to an instruction that it cannot understand), it interrupts its work and displays an error message.

For most readers, syntax errors are not a big problem. For example, there are often poems without punctuation, but we can easily read them, although this often creates ambiguity in their interpretation. But Revision: 170 Basic concepts translators (and the Python interpreter is no exception) are very picky about syntax errors.

Even if Python finds even a minor typo in your program, it will immediately display a message telling you where it found it and exit. He will not be able to carry out such a program and therefore will reject it. In the first weeks of your software development practice, you'll likely spend a fair amount of time looking for syntax errors. As you gain experience, you will admit them less and less, and find them faster.

h1.6.2. Runtime errors The second type of errors usually occurs during program execution (they are usually called exceptions or, in short, exceptions). Such errors have another reason. If an exception occurs in a program, it means that something unexpected happened during execution: for example, an incorrect value was passed to the program, or the program tried to divide some value by zero, which is unacceptable from the point of view of discrete mathematics. If the operating system sends a request to terminate the program immediately, an exception is also raised. But in simple programs this is a fairly rare occurrence, so you may not encounter them right away.

h1.6.3. Semantic errors The third type of errors is semantic errors. The first sign that your program has a semantic error is that it executes successfully, i.e. no exceptions, but does not do what you expect it to do.

In such cases, the problem is that the semantics of the written program are different from what you had in mind. Finding such errors is a non-trivial task, because...

you have to look at the results of the program and figure out what the program actually does.

h1.6.4. Debugging process The old glitch is better than the new two.

Popular programmer saying The ability to debug programs for a programmer is a very important skill.

The debugging process requires a lot of mental effort and concentration, but it is one of the most interesting things to do.

Debugging is very similar to the work of a natural scientist. By studying the results of your previous experiment, you draw some conclusions, then change the program accordingly, run it, and begin analyzing the results again.

If the result obtained does not coincide with the expected one, then you will have to again understand the reasons that led to these discrepancies. If your hypothesis turns out to be correct, then you will be able to predict the result of the modifications to the program and will be one step closer to completing the work on it, or perhaps it will make you even more convinced of your delusion.

Therefore, to check the functionality of a program, it is not enough to check it once - you need to come up with all possible sets of input data that can somehow affect the stability of your system. Such sets of input data are called boundary values.

Sometimes the process of writing and debugging programs is divided not only in time, but also between members of the development team. But recently, so-called flexible development methodologies have become increasingly popular. In them, coding is not separated from debugging: the programmers who write the code are also responsible for preparing tests and identifying as many errors as possible during the coding process. This allows them to fully enjoy their work.

The Linux kernel, whose source code contains millions of lines, began as a simple program that Linus Torvalds(Linus Torvalds) studied the possibility of parallel execution of tasks on the Intel 80386 processor. One of Linus's early programs was a program that switched between two processes: printing the sequences AAAA and BBBB. This program later became Linux (Larry Greenfield, The Linux Users" Guide Beta Version 1).

So, programming is a process of gradually refining and debugging until the program does what we want. You should start with a simple program that does something simple, and then you can start building up its functionality by making small modifications and debugging the added pieces of code.

This way, at each step you will have a working program, which, to some extent, will allow you to judge how much work you have already done.

In subsequent chapters you will have the opportunity to practice debugging programs.

Some useful debugging tips are included in Appendix A - be sure to read it when you have free time, preferably towards the end of the study of the sixth chapter.

Revision: 170 Variables, operations and expressions Chapter 2. Variables, operations and expressions And finally, we get down to the actual programming. You can immediately launch the Python interpreter. It won't hurt if you test the examples on your computer and experiment with them. If you find any error or typo, write to [email protected]. Perhaps your name will appear on the list of book developers.

h2.1. Values ​​and Types All programs work with values. The value can be a number or a string.

For example, in the first program we already printed the string value "Hello world!" on the screen. In a similar way, we can output the number:

>>> print "Hello world!" and 12 belong to various types: str (from English string - string) and int (from English integer - integer)3. The interpreter distinguishes a string from a number by the quotes in which it is enclosed.

If there are integers, then, in theory, there should also be fractions. Let's try this command:

>>> print 2, 2 Here is the first example of a semantic error: we expected the interpreter to print a decimal number, but it mistook the comma as a separator between two integers and printed them separated by a space. In general, he misunderstood us, because the separator is fractional and whole parts numbers in Python, as in most other programming languages, are dot4:

>>> print 2. 2. If you are not sure what type a value is, you can check it like this:

>>> type("Hello world!") >>> type(12) >>> type(2.4) The string type is called str in Python, the integer type is called int, and the fractional type is float (from the English floating-point number - floating point numbers).

3 In some versions of Python, these types are called unabridged: string and integer.

4 This unusual for us method of separating the integer and fractional parts is the American standard for writing decimal fractions.

Revision: 170 Variables, operations and expressions Exercise. Conduct the following experiment yourself: check the value types "12" and "2.4"? What type are they and why?

Exercise. What happens if you try to convert the string "8.53" to an integer using the int() function? How to solve this problem?

h2.2. Type Conversion In the previous section we learned how to display integers - it's pretty easy to do, isn't it? But for the interpreter this task looks somewhat more complicated, because it has to convert them to strings before outputting numeric values.

A programmer can do this too - Python has a whole collection of built-in functions that can convert values ​​of one type to another. For example, the int() function converts a value to an integer type. If the conversion cannot be performed, an exception is thrown:

>>> int("32") >>> int("Hello") Traceback (most recent call last):

File "", line 1, in ?

ValueError: invalid literal for int(): Hello The int() function can cast to integer and fractional numbers, but remember that it simply discards when converting fractional part:

>>> int(3.99999) >>> int(-2.3) - The float() function converts integers and strings to fractional type.

>>> float(32) 32. >>> float("3.14159") 3. And finally, the str() function is responsible for converting to string type. This is what the print command pre-runs:

>>> str(32) "32" >>> str(3.14149) "3.14149" Revision: 170 Variables, operations and expressions It may seem strange that Python distinguishes the integer 1 from the fractional 1.0: it is the same number, but belong to different types. The fact is that the type of value determines how it is stored in memory.

h2.3. Variables Like any other programming language, Python supports the concept of variables, but with a slight difference. If in C++ or Pascal a variable is the name of a memory location in which a value is stored, then in Python a variable is a reference to a memory location. The difference, at first glance, is insignificant, but in fact it is a slightly different approach to organizing the storage of objects in memory. However, we are not particularly concerned about this for now.

In order to remember a value, you just need to assign it to a variable. This is done using a special assignment operator, which is denoted by the equal sign (=).

>>> message = "Hello world!" >>> n = >>> pi = 3. V in this example the variable message is assigned (or mapped) to "Hello world!", the variable n is assigned the value 12, and the variable pi is assigned the value 3.14159.

The easiest way graphical representation variables: write the name of the variable, draw an arrow, at the other end of which add the assigned value.

Such drawings are sometimes called state diagrams because they represent the state the variable is in, i.e. what value is currently assigned to it.

message УHello world! Ф n pi 3. The print command also works with variables:

>>> print message Hello world!

>>> print n >>> print pi 3. As you can see, the print command does not print the names of the variables, but their values. Variables, like values, have a type. Let's check this using the type() function:

>>> type(message) >>> type(n) >>> type(pi) Revision: 170 Variables, operations and expressions The type of a variable is the same as the type of the value assigned to it. Let's look at another example:

>>> message = "Hello world!" >>> n = >>> type(message) >>> message = n >>> print message >>> type(message) This example is interesting for two reasons. First, it uses the ability to assign the value of one variable to another. The message = n construct works similarly to assigning a value to a variable: the message variable is assigned the value of the variable n. In this case, the value 12 is stored in memory only once - Python uses memory quite economically.

message УHello world! Ф n Secondly, as can be seen from the example, the message variable, after assigning the value n to it, changed its type. Not every programming language can do this so easily.

h2.4. Variable Names and Keywords As Frederick P. Brooks, Jr.5 noted, the most exciting thing about being a programmer is that he works with ideas in their purest form: he writes abstract ideas in formal languages ​​so that they make the work of other people easier. .

To transform an abstract idea, unmanifested in the material world, into program code, it is necessary to identify entities and actions, come up with names for them in order to manage them, and trace the connections between them and their properties. You probably guessed that the names of the entities with which the programmer works are variables. Therefore, it is worth choosing meaningful variable names.

Variable names can be of arbitrary length, but try to choose names that are neither too short nor too long - the readability of the program depends on this.

When composing variable names in Python, you can use any Latin letters, numbers, and the _ sign (underscore). The underscore can be used to 5 Frederick P. Brooks, Jr. led the famous IBM OS/360 project;

he is the author of the No Silver Bullet principle (NSB - There is no Silver Bullet, in the sense of a universal means of combating monster projects). We are talking about his book The Mythical Man-Month, or how software systems are created.

Revision: 170 Variables, operations and expressions separating words that make up the variable name: for example, user_name or full_price. But variable names cannot begin with a number.

>>> 1message = "Hello world!" File " ", line 1message = "Hello world!" ^ SyntaxError: invalid syntax >>> price_in_$ = File " ", line price_in_$ = ^ SyntaxError: invalid syntax >>>>", line>

>>> print = "Some message" File " ", line print = "Some message" ^ SyntaxError: invalid syntax This is a familiar situation, isn't it? Let's analyze what we received. We tried to use the print command as a variable name and received a similar error, meaning word>

Indeed, the words>

The total version in Python is 2.3. 29 keywords are reserved:

Revision: 170 Variables, operations and expressions and del for is raise assert elif from lambda return break else global not try>

Also keep in mind that the interpreter distinguishes between capital and small letters, i.e.

message and Message will be different variables.

Exercise. Write a program that verifies that the Python interpreter distinguishes between lowercase and lowercase capital letters in variable names.

h2.5. Expressions In the first chapter, we already encountered the concept of expressions in a general form and used them in the program. Let's define this term. An expression is a sequence of syntactic units that describes an elementary action in a programming language. For example, print "Hello world!" and message = n are expressions.

When you type an expression on the command line, the interpreter executes it and prints the result, if any. The result of the expression print "Hello world!" is the line: Hello world!. The assignment expression produces nothing.

Scripts typically contain a sequence of expressions, and the results of the expressions are printed as they are executed. For example, let's run a script containing the following expressions:

print x = print x This script will output the following:

Again, the assignment expression does not produce any output.

h2.6. Executing Expressions Essentially, an expression is a sequence of values, variables, and operators.

If you write an expression, the interpreter will execute it and display:

>>> 1 + The value itself is treated as an expression, just like a variable:

Revision: 170 Variables, operations and expressions >>> >>> x = >>> x But executing and outputting the result of executing an expression is not exactly the same:

>>> message = "Hello world!" >>> message "Hello world!" >>> print message Hello world!

When Python outputs the value of an expression in command mode, it uses the same format that is used when entering that value. For example, when outputting strings, it encloses them in quotes. The print command also prints the value of an expression, but in the case of strings, it prints the contents of the string without the quotes.

In scripts, expressions do not output anything at all unless they contain a print statement.

For example, the following script does not output a single line:

3. "Hello, World!" 1 + Exercise. Modify the script from the previous example so that it prints the values ​​of all four expressions.

In command mode, the Python interpreter stores the result of the last expression in a special variable _ (underscore). You can view the result of the last expression and use it in your expressions:

>>> 1.25 + 2. >>> print _ 2. >>> 5 + _ 7. Therefore, Python is quite convenient to use as a simple calculator. In the following sections, we will understand what operations the Python interpreter is capable of performing.

Revision: 170 Variables, operations and expressions 32.7. Operators and operands Operators are special characters (or sequences of characters) that represent certain operations. For example, the sign + denotes addition, and the sign * denotes multiplication. The values ​​on which the operation is performed are called operands.

All of the following expressions are correct from Python's point of view:

20+32 hour-1 hour*60+minute/60 5**2 (5+9)*(15-7) The meaning of most of them is not difficult to understand. The meanings of the symbols +, -, * and / in Python are the same as in mathematics. Parentheses are used to group operations, and two asterisks (**) denote the operation of exponentiation.

If the operand is a variable, then before the expression is evaluated, the value pointed to by the variable is substituted in its place.

Addition, subtraction, multiplication and exponentiation work in the same way we are familiar, but division works a little differently. The following example illustrates this:

>>> minute = >>> minute/ The value of the minute variable is 59;

The result of dividing 59 by 60 should be 0.98333, not 0. The reason for this discrepancy is that Python performs integer division.

When both operands are integers and Python assumes that the result must also be an integer. Therefore, integer division always discards the fractional part.

How to get fractional results? It is enough to forcefully convert one of the operands to a fractional number:

>>> minute = >>> float(minute) / 0. Another option:

>>> minute = >>> minute / 60. 0. If one of the operands belongs float type, then the second one is automatically converted to this type, as to a more complex one.

h2.8. Order of Operators Most programming languages ​​allow you to group multiple operators in one expression. This is convenient, for example, if you need to calculate the percentage ratio of two quantities:

Revision: 170 Variables, operations and expressions >>> print 100 * 20 / 80, "%" 25% This example calculates the percentage of two numbers: 20 and 80. After the result of the expression, the % symbol is displayed - the interpreter calculates the arithmetic expression and displays the result , and then adds the line after the comma.

When there is more than one operator in an expression, the sequence of operations depends on the order in which they appear in the expression, as well as on their precedence. The priorities of operators in Python completely coincide with the priorities of mathematical operations.

The highest priority is given to parentheses, which allow you to change the sequence of operations. Thus, the operations in parentheses are performed first.

For example, 2*(3-1) is equal to 4, (1+1)**(5-2) is 8. It is also convenient to use parentheses to make expressions easier to read, even if their presence in the expression does not affect result: (100*20)/80.

The next priority is the exponentiation operation, so 2**1+1 is 3, not 4, and the expression 3*1**3 will result in 3, not 27.

Multiplication and division have the same priority, higher than addition and subtraction. 2*3-1 equals 5, not 4;

2/3-1 is -1, not 1 (the result of integer division is 2/3=0).

Operators with the same precedence are executed from left to right. So in the expression 100*20/80, the multiplication is done first (the expression becomes 2000/80);

then division is performed, resulting in a value of 25. If the operations were performed from right to left, the result would be different.

Exercise. Change the expression 100*20/80 so that the sequence of operations is reversed. What result did you get after doing it and why?

h2.9. Simple operations on strings Generally speaking, you cannot perform the same operations on strings as on numbers, so the following examples will not work:

message-1 "Hello"/123 "Hello"*"world!" "15"+ But the + operator works with strings, although it denotes a different operation: concatenation or concatenation of strings.

>>> str1 = "Hello" >>> str2 = "world" >>> print str1 + str2 + "!" Hello world!

Notice that the second line starts with a space. The space is a character just like any other.

The * operator can also be used with strings, but only if one of the operands is an integer. In this case, the * operator symbolizes the string repetition operation (or iteration). For example, "Fun"*3 will produce the result "FunFunFun".

Revision: 170 Variables, operations and expressions You can trace the analogy between operations on numbers and operations on strings: just as 4*3 is equivalent to 4+4+4, "Fun"*3 is equivalent to "Fun"+"Fun"+"Fun ".

But on the other hand, concatenation and repetition have several significant differences from addition and multiplication.

Exercise. All operations in mathematics are classified according to their properties (commutativity, associativity, etc.). What properties do addition and multiplication have that concatenation and repetition do not?

Don’t be lazy to look into a mathematical reference book - understanding the properties of the objects you operate with will give you great advantages.

Exercise. What result will be obtained after executing the expression "hello"+"world"*3? What conclusions can be drawn based on this result?

h2.10. Composition Finally, let's look at another important concept: composition. Without noticing it, we have already encountered it.

The entire world around us consists of component parts. For example, houses are made of bricks or building blocks, bricks, in turn, are made of small grains of sand, and those are made of molecules and atoms. In order to model phenomena in the surrounding world, a model building tool must also be able to assemble small objects into systems, which in turn will be combined into even more complex complexes.

A modeling tool (i.e. describing various objects and situations) for a programmer are programming languages. All high-level languages ​​implement the ability to create systems from simpler elements, or composition.

For example, we know how to add two numbers and how to display the resulting value.

So we can do it in one expression:

>>> print 17 + In fact, addition and output of a value do not occur at the same time: the expression is first evaluated, and then the result is output. But you can output the result of any expression this way, no matter how complex it is.

Expressions can be built from other expressions in several ways.

Consider this example:

>>> percentage = 100 * 20 / 80;

print percentage First, expressions can be nested inside each other. In particular, the assignment expression has such a structure that to the left of the assignment sign there must be the name of the variable to which the result of evaluating the expression to the right of the assignment operator is assigned. In turn, the expression on the right side is also complex:

the calculation is carried out in the order determined by the priorities of the operations. The division operation in our example takes the result of multiplication as its first operand - this is also an example of nesting expressions.

Revision: 170 Variables, operations and expressions The second option for arranging expressions is following. In the example, two expressions (the assignment expression and the expression for displaying the value of the percentage variable) are separated by a semicolon. These expressions are executed one after the other. Generally speaking, any program is a sequence of expressions. If the expressions are located on separate lines, then it is not necessary to put a semicolon at the end of each expression: in in this case The expression separator is the line terminator. This rule applies to Python, but in C++ and Pascal, expressions must end with a semicolon.

Later you will see that composition can be used to combine any syntactic units and expressions, including subroutine calls.

Exercise. Try running the command on the Python interpreter command line: 100 * 20 / 80 = percentage. What result did you get and why?

Revision: 170 Functions Chapter 3. Functions h3.1. Subroutines Back in the days of address programming, it was noticed that some parts of a program can be used more than once if the value of some parameter is changed. For example, a program may calculate a value using a certain formula several times, but each time the values ​​entered into the formula change.

Programmers began to generalize solutions to small, repeating subproblems and access parts of the program with these solutions where needed. Programs ceased to be linear, so they began to resemble a pack of pasta, because... consisted of chains of instructions, and switching between them was carried out using commands of conditional or unconditional transitions and labels defining the beginning of each pasta.

To some extent, this significantly complicated the process of debugging and expanding the functionality of programs, but, on the other hand, it opened up new opportunities for programmers: firstly, programs began to take up less space, and they became easier to navigate;

secondly, correcting errors has become much easier, because programmers no longer needed to search for all parts of the code that were repeated with minor changes in order to fix an error found in one of them - it was enough to fix this defect in just one place.

Idea reuse code is very important in programming, because without it, the support and development of modern software products Given their complexity, this represents an almost impossible task. At the very least, the cost of owning programs would be much higher without it, and their use would become unprofitable in most cases.

Structured programming languages ​​implement the concept of code reuse in several different ways. One of them is writing subroutines.

Subroutines represent the same set of instructions as the program itself, but they solve less complex problems. Subroutines can receive a certain set of parameters as input and return some value as output.

IN Pascal language There are two types of subroutines: procedures and functions. In Python, as well as in C++, subroutines are implemented in a more general form, so there is no such division - in these languages ​​there are only functions.

Sometimes subroutines are grouped into so-called modules - special files that store a description of these functions, which can be connected and used in any part of the project or even in other projects. How to create and connect modules in Python is described in detail in Appendix B. But for now, let's start mastering the functions.

Revision: 170 Functions 3.2. Function calls We have already encountered function calls when defining and converting value types and variables:

>>> type("Hello world!") >>> int("32") The function that determines the type of a value or variable is called type();

The value or variable to be converted must come after the function name in parentheses - this is called the function argument. As you can see from the example, the int() function is called in a similar way.

Thus, to call a function, you just need to type its name and list the parameters in parentheses, and if you don’t need to pass parameters, then you don’t have to write anything in parentheses. For example, in the str() function, the first parameter is optional, i.e. it can be omitted:

>>> str() "" 3.3. Help System Python has many functions defined that allow you to solve various problems.

Some of them are grouped by purpose and placed in separate modules. In the next section, we'll learn how to import modules and use functions from them, but first we'll figure out how to determine what a particular function is intended for.

This skill will be very useful to you in the future, because... It is often quite difficult to guess the purpose of functions by their names.

To simplify the programmer's work, Python provides a built-in variable doc (begins and ends with pairs of underscores), which usually stores minimal reference information:

>>> print str.doc str(object) -> string Return a nice string representation of the object.

If the argument is a string, the return value is the same object.

>>> The str() function introduced itself and displayed information about itself: what parameters it takes, what type of value it returns, and briefly described what it does.

Starting with version 2.2, Python introduced a help system, implemented in the form of the help() function. This function takes the name of any object (including a module or function) as a parameter and displays help information about it.

Exercise. Check out background information functions str(). Please note that the help() function will not work in Python versions below 2.2. Exit the help system using the [Q] key.

Revision: 170 Functions 3.4. Importing modules and mathematical functions In addition to the simplest operations on numbers, which we have already considered, Python is capable of calculating values ​​of more complex ones mathematical functions:

trigonometric, logarithmic, etc. In order to access these functions, you need to import or connect a special module in which the definitions of these functions are stored. You can do this using the following instructions:

>>> import math >>> This command imports the math module. Python supports partial import of modules (you can read more about this in Appendix B), but we don't need it yet.

So, we have imported a module with a description of mathematical functions and now we will try to call one of them from it. First, let's determine which functions and constants are defined in the module:

>>> dir(math) ["doc", "file", "name", "acos", "asin", "atan", "atan2", "ceil", "cos", "cosh", "e ", "exp", "fabs", "floor", "fmod", "frexp", "hypot", "ldexp", "log", "log10", "modf", "pi", "pow", "sin", "sinh", "sqrt", "tan", "tanh"] >>> As a result of executing this command, the interpreter printed all the names defined in this module. Among them is the doc variable. In order to access a variable or function from an imported module, you must specify its name, put a dot and write required name:

>>> print math.doc This module is always available. It provides access to the mathematical functions defined by the C standard.

>>> print math.pi 3. >>> decibel = math.log10(17.0) The first line of the example prints a description of the module;

the fourth is the value of the constant, and the sixth calculates the value of logarithm 17 in base 10. In addition to the decimal logarithm, the module also defines a natural logarithm (i.e. with base e = 2.7182818284590451): math.log(). One more example:

>>> height = math.sin(45) >>> print height 0. If you studied trigonometry, you probably remember that the sine of 45 degrees is equal to the square root of 2 divided by 2. Let's check the result of the function calculation:

Revision: 170 Functions >>> math.sqrt(2) / 2. 0. The results were different. Why? Did the developers make a mistake? It is quite likely that no one is immune from mistakes. But, before writing a bug report and sending it to the developers, let's take a look at the help for this function:

>>> help(math.sin) Help on built-in function sin:

sin(...) sin(x) Return the sine of x (measured in radians).

(END) From the help you can see that trigonometric functions take the angle value in radians as a parameter. Press [Q] to exit the help system with a feeling of pride: now we know how the math.sin() function works;

Let's convert to radians:

>>> degrees = >>> angle = degrees * math.pi / 180. >>> height = math.sin(angle) >>> print height 0. Now the results are the same - everything is correct.

Exercise. Run the following instructions on the command line of the Python interpreter version 2.2 or higher:

>>> import math >>> print math.doc...

>>> help(math) Read the description of the module and its functions. All the help won't fit on the screen, but you can scroll through the text using the arrow keys. Exit the help system using the [Q] key.

If you want, you can play around with these functions by writing a few simple programs using them. Where can they be used?

h3.5. Composition In the second chapter we already looked at composition in relation to arithmetic operations and simple expressions. But composition also allows you to combine function calls: a function can take as a parameter any expression that returns a value that falls within the scope of its definition;

on the other hand, a function call (more precisely, the result of its execution) can be used as an operand:

>>> x = math.sin(math.asin(math.sqrt(2) / 2.0) + math.pi / 2) >>> print x 0. >>> Let's look at this example. The first operation the parser encounters when parsing this expression is assigning the value of the expression to the right of the = sign to the variable x. Before assignment, the interpreter must evaluate the value of this expression, i.e. calculate the sine of the value of the expression math.asin(math.sqrt (2) / 2.0) + math.pi / 2, which in turn is equal to the sum of the values ​​of the subexpressions math.asin(math.sqrt(2) / 2.0) and math.pi / 2. The first of them is calculated in a similar way: first, the value of the expression in parentheses is calculated, and then the math.asin() function is called, to which the resulting expression is passed as an argument. The second subexpression is /2. Having calculated the sum of these two subexpressions, the interpreter passes the resulting value as an argument to the math.sin() function and assigns the result to the variable x.

Write a program that calculates the roots of the quadratic equation ax2+bx+c=0, a0 from the coefficients of this equation. The coefficients must be entered at the beginning of the program into variables a, b and c.

Try setting the variables a, b and c to 1, 0 and -1 respectively. The program should output the values ​​1.0 and -1.0. Check if your results are as expected.

When experimenting with other coefficients, keep in mind that there are equations that have no solutions (such equations have a discriminant less than zero), so do not be alarmed if an error of the form appears in your program: ValueError: math domain error. A little later we will find out how to avoid this.

h3.6. Creating Functions So far we have used Python's built-in functions and functions from the modules that come with Python. But the power of structured programming languages ​​is that we can create our own functions, and this is done quite simply. IN structured programming A function is a named sequence of expressions that performs a required operation. Python has a special function definition operator with the following syntax:

def FUNCTION_NAME(PARAMETER_LIST):

SEQUENCE OF EXPRESSIONS The rules for choosing function names are completely similar to the rules for choosing variable names described in the previous chapter. The parameter list defines a set of values ​​that can be passed to the function as input data - parameters are listed separated by commas. The first line of the definition is usually called the function header, denoted keyword def (from the English define - to determine). A function header in Python ends with a colon. It can be followed by any number of expressions, but they must be written offset from the beginning of the line. For Revision: 170 Functions of such an offset, you can use one or more spaces, but, perhaps, it is most convenient to use a tab character (key) instead of spaces. Let's write and test our first function;

to complete the sequence of expressions that make up the body of the function, just press the key again (in an editor that supports auto-indentation, you will also have to press to remove the automatically added indent):

>>> def printAnything(object):

Print object...

>>> printAnything("Some string") Some string >>> number = >>> printAnything(number) In the first two lines of the example, we defined the PrintAnything() function, which prints the object passed as a parameter. We can pass a string or a number to this function, which is what we tried to do in the fourth and seventh lines of the example.

The results obtained coincided with the expected ones, but let's not dwell on this and perform another experiment.

What if you pass the function name as a parameter? Let's call PrintAnything(), indicating its name in parentheses:

>>> printAnything(printAnything) >>> Python printed information about the function: its name and the address in memory where it is stored! In this case, the address is 0x80d7554, but this address on your computer may be different. Now let's open a text editor and write a program like this:

def printHello():

print "Hello!" def runFunction(function_name):

function_name() runFunction(printHello) Save the program in a file named prog2.py and run it from the command line (in the Windows operating system, just double-click the left mouse button on the icon of this file6):

$ python prog2.py Hello!

6 Don’t forget to write a command to wait for a key press in the last line of the program, as described in the section Running programs written in Python (see Introduction).

Revision: 170 Functions You probably already understand what Python did when we called the runFunction() function and passed it the name of the printHello() function as a parameter: it replaced function_name with the value of the passed parameter and thus called the printHello() function. It's a rare programming language to have this kind of flexibility. In C++ or Pascal, this is done in a far from trivial way.

Also keep in mind that you cannot call a function before it has been defined - this will throw an exception.

Exercise. Convert the program for calculating the roots of a quadratic equation into the printRoots() function. The parameters of this function must be the coefficients of the quadratic polynomial: a, b and c. Having calculated the roots of the equation, the function should print them.

Exercise. Write a function that calculates the distance between two points on a plane (coordinates (x1, y1) and (x2, y2) are given).

distance x1, y1, x2, y2= x2 -x12 y2 - y 3.7. Parameters and Arguments So far we've learned how to create our own functions and differentiate between function definitions and function calls. Now let's define the terminology: what is the difference between a function parameter and its argument? There is a big difference, but you might not notice it.

Function parameters are a list of variables that are assigned the values ​​passed when calling this function. And the passed values ​​themselves are called arguments. In its body, a function operates with parameters, but not with arguments. Let's look at an example from the previous section:

>>> def printAnything(object):

Print object...

>>> printAnything("Some string") Some string >>> number = >>> printAnything(number) Here the variable object is the parameter, and the string "Some string" and the variable number are the arguments. Thus, it is correct to say pass an argument or pass a value as a parameter, but not to pass a parameter to the function. Try not to confuse these concepts.

h3.8. Local variables Let's return to the PrintRoots() function for finding roots of a quadratic equation. It looks something like this:

def printRoots(a, b, c):

Revision: 170 Functions D = b**2 - 4 * a * c import math x1 = (-b + math.sqrt(D)) / 2 * a x2 = (-b - math.sqrt(D)) / 2 * a print "x1 =", x1, "\nx2 =", x The sequence of characters \n in the last line of the function body instructs the print command to go to new line. The function body defines three variables: D, x and x2. Such variables are called local, because they can only be accessed in the function body itself. After the function is completed, they are erased from memory. The following program can illustrate this:

def printRoots(a, b, c):

D = b**2 - 4 * a * c import math x1 = (-b + math.sqrt(D)) / 2 * a x2 = (-b - math.sqrt(D)) / 2 * a print " x1 =", x1, "\nx2 =", x printRoots(1.0, 0, -1.0) print D If you run it, the interpreter will immediately display an error like this after the PrintRoots() function completes:

$ python prog5.py x1 = 1. x2 = -1. Traceback (most recent call last):

File "prog5.py", line 12, in ?

print D NameError: name "D" is not defined Why was this behavior chosen? How do you think? Let's modify our program this way:

def printRoots(a, b, c):

D = b**2 - 4 * a * c import math print "In function D = ", D x1 = (-b + math.sqrt(D)) / 2 * a x2 = (-b - math.sqrt( D)) / 2 * a print "x1 =", x1, "\nx2 =", x Revision: 170 Functions D = "test" print "Before function call D = ", D printRoots(1.0, 0, -1.0) print "After function call D = ", D Let's run the program and analyze the result.

$ python prog5.py Before function call D = test In function D = 4. x1 = 1. x2 = -1. After function call D = test So, after defining the printRoots() function, we assigned the value "test" to variable D and checked the result: the string "test" was printed. Then they called the printRoots() function, in the body of which, after assigning the result of calculating the discriminant formula to variable D, the value of variable D is also displayed: 4.0. After the function completes, we print the value of variable D again: this time the assigned value is again equal to the string "test".

In fact, D in the main program and D in the body of the printRoots() function are two different variables. You can check this by slightly modifying our program.

Let's use the id() function. It returns the address of an object in memory. The modified program will look something like this:

def printRoots(a, b, c):

D = b**2 - 4 * a * c import math print "In function D = ", D, "\nAdress:", id(D), "\n" x1 = (-b + math.sqrt(D )) / 2 * a x2 = (-b - math.sqrt(D)) / 2 * a print "x1 =", x1, "\nx2 =", x D = "test" print "Before function call D = ", D, "\nAdress:", id(D), "\n" printRoots(1.0, 0, -1.0) print "After function call D = ", D, "\nAdress:", id(D), "\n" The result of the program will be as follows:

$ python prog5.py Before function call D = test Adress: Revision: 170 Functions In function D = 4. Adress: x1 = 1. x2 = -1. After function call D = test Address: On your computer, the addresses may be different, but you can draw the same conclusions: the addresses D in the main program and D in the body of the printRoots() function are different.

Q.E.D.

Exercise. Are function parameters local variables?

h3.9. Execution flow As already mentioned, with the advent of functions (and procedures), programs ceased to be linear, in connection with this, the concept of execution flow arose - the sequence of execution of instructions that make up the program.

The execution of a program written in Python always begins with the first expression, and subsequent expressions are executed one after another from top to bottom. Moreover, function definitions do not affect the execution flow in any way, because The body of any function is not executed until the corresponding function is called.

When the interpreter, parsing the source code, comes to a function call, it, having calculated the values ​​of the arguments, begins executing the body of the called function and only after its completion proceeds to parsing the next instruction.

Everything is quite simple, although tracing the flow of execution in complex programs often turns out to be a non-trivial task, because in the body of any function another function can be called, which can also contain function calls in its body, etc.

However, the Python interpreter remembers where each function was called from, and sooner or later, if no exceptions are thrown during execution, it will return to the original call to move on to the next instruction.

So, imagine that we have three functions: f1(), f2() and f3(). Moreover, they call each other like this:

print "f1() begins" print "Hello world!" print "f1() ends" def f2():

print "f2() begins" f1() Revision: 170 Functions print "f2() ends" def f3():

print "f3() begins" f2() print "f3() ends" print "Main program begins" f3() print "Main program ends" In order to track the sequence of operations, we have added commands that will signal when it begins and each function ends.

So, let's run the program and see what we got:

$ python prog6.py Main program begins f3() begins f2() begins f1() begins Hello world!

f1() ends f2() ends f3() ends Main program ends Let's analyze the result. As already mentioned, function definitions do not affect the execution of the main program in any way. The exception is when the interpreter encounters a syntax error in the body of a function: even if it is not yet time to execute it, it will print an error message and exit.

The main program begins by displaying a message about its start, then the f3() function is called, which, when presented, calls the f2() function. That, in turn, does the same, calling f1(). f1() also prints a message about its start, then a test greeting to the world and a message about its completion. The thread of execution returns within the body of the f2() function to the point where f1() was called, after which the next instruction is executed, printing a message indicating that the f2() function has completed its work. As you may have guessed, the flow of execution returns to the body of the f3() function, and after its completion, to the main program.

h3.10. Stack diagrams For clarity, you can draw so-called stack diagrams. They are called that for a reason: they represent a call stack.

A stack is a special data structure that resembles a stack of plates, because interaction with the stack is carried out according to a special LIFO rule (Last In First Revision: 170 Out functions - last in, first out). Returning to the analogy of a stack of plates, we stack the plates one on top of the other and pick them up starting from the top. A little later we will learn how to model a stack and some other data structures that are often used to solve various tasks, but for now, limiting ourselves to an intuitive understanding of the stack, let’s draw a stack diagram for the example from the previous section.

F1() begins f1() ends f1() Hello world!

f2() begins f2() ends f2() f3() begins f3() ends f3() Main program begins Main program ends main In this diagram, the flow of execution is indicated by arrows, subprograms are indicated by rectangular blocks;

The lines output by the program are added to the right and left of the stack diagram. At the bottom of the stack is the main program (denoted main);

Accordingly, it cannot complete until all the functions that are above it in the call stack complete. Thus, using a stack to track the flow of execution is the most natural and simple solution.

During program execution, the call stack can grow and empty many times.

When an exception occurs in one of the functions, it is often quite difficult to understand under what conditions (or under what set of parameters) the failure occurred, because The same function can be called from different places in the program many times. Therefore, to facilitate the debugging process, the Python interpreter displays not only the line number where the exception occurred, but also the entire call stack at the time the exception occurred.

Let's tweak our program a little so that a division by zero exception is thrown in the f1() function, replacing the greetings to peace output with the expression a = 1/0:

print "f1() begins" a = 1/ print "f1() ends"...

Now let's run this program:

$ python prog6.py Main program begins f3() begins f2() begins f1() begins Traceback (most recent call last):

Revision: 170 Functions File "prog6.py", line 17, in ?

f3() File "prog6.py", line 13, in f f2() File "prog6.py", line 8, in f f1() File "prog6.py", line 3, in f a = 1/ ZeroDivisionError: integer division or modulo by zero After the message about the start of execution of the f1() function, the interpreter displayed the so-called traceback (Russian-speaking programmers usually say traceback or simply trace). Traceback contains not only the names of functions from the call stack, but also the line numbers from which each call was made. In addition to the numbers, the name of the file with the program is also indicated, because the project may contain more than one module. So it becomes much easier to find and fix the error.

h3.11. Functions that return a result Finally, let's get acquainted with another important feature of functions. It is not difficult to imagine a situation where the results of a function may be needed for further operation of the program. But after the function completes its work, all variables that were initialized in its body are destroyed, because they are local.

Therefore, if it is necessary to return the result of a function to the subroutine from which it was called, the return command is used for further processing. It looks something like this:

>>> def getSum(x,y):

Z = x + y... return z...

>>> print getSum(1,3) >>> As you can see, the value returned by the function is perceived by the interpreter as the result of the expression that calls this function.

In Python, functions are capable of returning multiple values ​​at the same time7. For example, take the function of calculating the roots of a quadratic equation:

>>> def PrintRoots(a, b, c):

D = b**2 - 4 * a * c... import math 7 By the way, in Pascal and C++ it is impossible to return several values ​​from a function at once using standard tools. This is another convenience that Python provides.

Revision: 170 Functions... x1 = (-b + math.sqrt(D)) / 2 * a... x2 = (-b - math.sqrt(D)) / 2 * a... return x1, x...

>>> print PrintRoots(1.0, 0, -1.0) (1.0, -1.0) In addition, we can assign the results of the function to several variables at once:

>>> x1, x2 = PrintRoots(1.0, 0, -1.0) >>> print "x1 =", x1, "\nx2 =", x x1 = 1. x2 = -1. >>> Most likely, you have already guessed that Python’s built-in functions return values ​​in exactly the same way.

Revision: 170 Computer graphics Chapter 4. Computer graphics /* turtle module*/ Revision: 170 Logical expressions, conditions and recursion Chapter 5. Logical expressions, conditions and recursion h5.1. Comments in programs Any fool can write a program that the compiler will understand. Good programmers write programs that other programmers can understand.

Martin Fowler, "Refactoring" As your programs get larger, you'll sooner or later run into one problem: they'll become harder to read. Ideally, a program should be read as easily as if it were written in a natural language, but, on the one hand, natural languages ​​still do not have such a clear formal form for describing objects and processes, and on the other hand, excessive formalization often leads to complication descriptions of simple things. Therefore, to improve the understandability of code, it is useful to annotate it in natural language, and most programming languages, not excluding Python, provide this feature.

Jokers say that after a hard day at the computer, a typical programmer goes home, sits down at the PC and thus relaxes. But the truth is actually much worse than this joke: many of us, when we come home from work, devote the remaining time before bed... to programming microcontrollers. 🙂 Ordinary people don’t understand, but Arduino, Teensy or ESP are really a very good hobby. Their only drawback is the need to program at a fairly low level, if not in Assembler, then in Arduino C or Lua. But now Python has appeared in the list of languages ​​for microcontrollers. More precisely, MicroPython. In this article I will try to demonstrate its capabilities as much as possible.

Where did it all start?

It all started with a Kickstarter campaign. Damien George, a developer from England, has designed a microcontroller board specifically for Python. And the campaign took off. The amount originally announced was £15,000, but it ended up raising six and a half times that amount - £97,803.

Why is this board better?

    Power - MP is more powerful compared to Arduino microcontroller, 32-bit ARM processors like STM32F405 (168 MHz Cortex-M4, 1 MB of flash memory, 192 KB of RAM) are used here.

    Ease of use - the MicroPython language is based on Python, but is somewhat simplified so that commands for controlling sensors and motors can be written in just a few lines.

    No compiler - to run a program on the MicroPython platform, there is no need to install additional software on your computer. The board is detected by the PC as a regular USB drive - just drop a text file with code onto it and reboot, the program will immediately start executing. For convenience, you can still install a terminal emulator on your PC, which makes it possible to enter code elements from the computer directly onto the platform. If you use it, you won’t even have to reboot the board to check the program; each line will be immediately executed by the microcontroller.

    Low cost - in comparison with Raspberry Pi, the PyBoard platform is somewhat cheaper and, as a result, more accessible.

  • Open platform - just like Arduino, PyBoard is an open platform, all circuits will be publicly available, which means you can design and create such a board yourself, depending on your needs.

So what, only the official fee?

No. For all its advantages, PyBoard (that’s the name of the board from the MicroPython developer) is quite an expensive pleasure. But thanks to the open platform, many popular boards can already run MicroPython, built specifically for it. Currently there are versions:

  • for BBC micro:bit - British development, positioned as an official teaching aid for computer science lessons;
  • Circuit Playground Express is a development of the famous company Adafruit. This is a board that includes LEDs, sensors, pins and buttons. By default it is programmable using Microsoft MakeCode for Adafruit. It is a block-based (Scratch-like) “code” editor;
  • ESP8266/ESP32 is one of the most popular boards for IoT development. It could be programmed in Arduino C and Lua. Today we will try to install MicroPython on it.

Preparing for work

Before writing programs, you need to configure the board, install firmware on it, and install the necessary programs on the computer.

INFO

All examples have been checked and tested on the following equipment:

  • NodeMCU ESP8266-12E board;
  • L293D motor driver;
  • I2C display 0.96″ 128 × 64;
  • Adafruit NeoPixel Ring 16.

Controller firmware

To flash the board firmware we will need Python. More precisely, not even himself, but the esptool utility, distributed using pip. If you have Python installed (no matter what version), open a terminal (command line) and type:

Pip install esptool

After installing esptool, you need to do two things. The first thing is to download the firmware version for ESP8266 from the official website. And secondly, determine the board’s address when connecting to a computer. The easiest way is to connect to your computer, open the Arduino IDE and look at the address in the list of ports.

To make it easier to understand, the board address in the example will be /dev/ttyUSB0, and the firmware file is renamed esp8266.bin and is located on the desktop.

Open a terminal (command line) and go to the desktop:

CD Desktop

Formatting the board's flash memory:

Esptool.py --port /dev/ttyUSB0 erase_flash

If errors occur during formatting, then you need to enable the firmware mode manually. We press the reset and flash buttons on the board. Then we release reset and, without releasing flash, we try to format again.

And load the firmware onto the board:

Esptool.py --port /dev/ttyUSB0 --baud 460800 write_flash --flash_size=detect 0 esp8266.bin

Interaction with the board

All interaction with the board can occur in several ways:

  • via Serial port;
  • via a web interpreter.

When connecting via the Serial port, the user sees an almost ordinary Python interpreter in his terminal (in his command line).



For connecting via Serial there is different programs. For Windows you can use PuTTY or TeraTerm. For Linux - picocom or minicom. As a cross-platform solution, you can use the Arduino IDE port monitor. The main thing is to correctly identify the port and specify the data transfer rate of 115200.

Picocom /dev/ttyUSB0 -b115200

In addition, several programs have already been created and posted on GitHub to facilitate development, for example EsPy. In addition to the Serial port, it includes a Python file editor with syntax highlighting, as well as a file manager that allows you to download and upload files to the ESP.



But all of the above methods are good only when we have the opportunity to directly connect to the device using a cable. But the board can be integrated into some device, and disassembling it just to update the program is somehow suboptimal. Probably, it was for such cases that WebREPL was created. This is a way to interact with the board through a browser from any device located on the same local network, if the board does not have a static IP, and from any computer, if such an IP is present. Let's set up WebREPL. To do this, connect to the board and dial

Import webrepl_setup

A message appears about the status of WebREPL autorun and asks you whether to enable or disable its autorun.

WebREPL daemon auto-start status: enabled Would you like to (E)nable or (D)isable it running on boot? (Empty line to quit) >

After entering q, a message appears about setting an access password:

To enable WebREPL, you must set password for it New password (4-9 chars):

We enter it and then confirm. Now after a reboot we will be able to connect to the board via Wi-Fi.

Since we have not configured the board to connect to the Wi-Fi network, it works as an access point. The name of the Wi-Fi network is MicroPython-******, where I replaced part of the MAC address with asterisks. We connect to it (password - micropythoN).

  • Python,
  • Website development
  • If you are looking for an answer to the question: “Which programming language to choose first,” then in about 90% of all cases you will be offered Python - as the easiest language to learn. And it is obvious that a certain number of people who have not learned programming before will choose Python because of these recommendations. And here we have a problem, which will be discussed below. Of course, with a description of how I got to this life.

    About Me

    Even during my student years, I realized that my specialty was not as rosy as it seemed to me at 18 years old. So I started thinking about how to earn adequate money. And after listening to stories about how my cousin received crazy money at that time in 1C, I also decided to connect my life with IT.

    Initially, these were template sites using website builders and WordPress, then I got involved in SEO, and at one point came across Habr, after which I decided to become a full-fledged programmer. I didn’t have higher mathematics, so I decided to choose a field where it was not required - web development.

    I had an obvious question: which language to choose - php/python/ruby. Having seen enough articles on Habré, I read some hate towards php after watching a couple of motivational videos from Yandex. I chose Python. I hope you know the advantages of language, so I won’t talk about it.

    Primary language training

    I combined language learning with my main job, so I read books, watched tutorials, and worked on small projects in the evening. In general, in a year I

    1) Studied books:

    • Mark Lutz - Learning Python
    • Mark Lutz - Python Programming
    • Chad Fowler – Programmer Fanatic
    • Bill Lubanovich - Simple Python
    2) Studied a lot of videos from Ukrainian/Bourgeois authors on Django
    3) Completed a course from codeacademy
    4) Mastered PyCharm

    Your first project

    Then I had the idea of ​​a small service on a very specific topic, which I decided to create in order to consolidate my knowledge of Python + Django.

    In creating the site I

    1) Studied books:

    • John Duckett - HTML and CSS. Website development and design
    • David Flanagan - JavaScript. Detailed Guide
    • Ben Forta - Learn SQL on your own.
    2) I studied the Django documentation for my tasks
    3) I studied the deployment of projects on Django Gunicorn + nginx + centOS

    My first normal project

    After the first adequate website failed, I decided to create something worthwhile, chose an idea, chose an implementation scheme, and completed it in the evenings in 3 months.

    The project has shown its viability (to this day it brings me some money, which I am incredibly happy about). And I decided to pump it up better.

    After reading the book “Percival H. - Test-Driven Development with Python,” I decided to write tests first based on Django components, then looked up the Selenium documentation, and already made external tests.

    I want to be cool

    Having opened vacancies for Python-Django developers, I looked at what else is usually required in such vacancies:
    • Django Rest Framework
    • Celery
    • Tornado/Twisted/asyncio (Choose one)
    • Class-based view Django
    • Angular/React (Choose one)
    Spent 3 months getting to know/trying these things. I also picked up the Python standard library + external parsing library beautifulSoup.

    You can't work without C/C++

    There is an opinion that without knowledge of C/C++, a programmer cannot call himself a programmer. Therefore, when I had free time, I got acquainted with the books:
    • Brian Kernighan – C Programming Language
    • Stanley B Lippman – C++ programming language. Basic course
    I read the books, tinkered with the code, looked at the compilation, looked at the code examples. In general, now I didn’t make big eyes at the mention of references, pointers, sorting, OOP and a bunch of different arrays with at different speeds processing an element depending on its position.

    I'm ready to fight!

    And here we come to the most important point. Having spent a total of 2 years learning all the elements of web programming that I mentioned above. I considered myself ready enough to apply for a position as a Python web developer. Of course, I didn’t know some things very well, some superficially, and some I didn’t know at all (for example, Flask), but the general understanding and skills were quite good.

    And here the problems with Python began, which people most often do not focus on. Namely, on the business demand for junior/pre-middle level Python developers.

    I entered the market with this question.

    Although at first glance it seems that there are quite a lot of vacancies in Python, when the specifics begin, everything changes dramatically.

    1. Immediately there is a large screening of vacancies where Python is exclusively an auxiliary language. Most often these are positions of Java developers, System Administrators, QA Automation. Also, there is now a large dropout in Data Learning, which requires a math education + the R language. With Python alone you won’t be able to find this vacancy.

    2. It turned out that in my city there are no vacancies for Python, literally none at all. Having expanded the search throughout the area, I also received unsatisfactory results. A couple of vacancies in PHP, where Python was a plus. When I opened the filter for the last 3 years, I also discovered that there were no vacancies for Python at all. Those. businesses in the provinces most often choose simpler and more popular technologies than Python.

    3. Having opened Python vacancies in a general search engine, I discovered the following trends:

    • 90%+ of vacancies are located in Moscow or St. Petersburg
    • 90%+ of vacancies require middle+ / senior level
    • ~100% of vacancies for junior positions in Moscow or St. Petersburg (most often from giants)
    In other words, the situation has turned out that if you do not live in Moscow, St. Petersburg and are not going to go to “conquer” them, then you have practically no place to get your first job.

    Of course, there are a couple of places where Python is still used, for example, in Kazan. But most often this is one company, where the vacancies are also very middle+ / senior.

    4. The option of searching for remote work at the current level also showed that employers are not ready to take such a risk. Little experience + remote work = this is some kind of fantasy.
    Nevertheless, I was still able to find a couple of options, but already during the initial interview it became clear that this was nonsense like: “You work for us for three months, and if the client pays for your work, we will pay you too.” Not the best option.

    5. I spoke with a couple of HR from large companies, they expressed this trend. “We usually hire people with at least a year of experience in Python, plus experience in another language (3+ years). Most often php/Java." In other words, they didn't consider hiring someone with just Python at all.

    6. After talking with guys from specialized forums, it became clear that this is a fairly typical situation. From their stories, it became clear that people, after a futile search, either went to work on php/1c, or somehow climbed through upwork/own project/test automation.
    But again, from case to case.

    In general, it turned out that Python is an excellent language that allows you to create powerful projects. And it just so happens that their concentration is in the capitals. And since these are complex projects, then employees are required at the middle+ level. Is a person who has just learned Python ready to get such a vacancy? Difficult!

    But there is another way!

    At the moment, in my city alone there are 24 vacancies for PHP of various levels (from small companies that need to support the current website to e-commerce giants that offer a consistent expansion of functionality). And about the same number of vacancies for 1C. And in about half of these vacancies they are ready to hire a person who at least knows something about programming. Most likely, these are not the most best places, but this is already the first job after which you will officially become an experienced programmer for HR.

    So in the end

    It turns out that you can learn the cool programming language Python and stay on the street. Or you can learn the “hated” php/1c and get a job. The quality of this work, of course, leaves many questions - but this is already experience.

    As for me, in my conditions (not going to Moscow/St. Petersburg), I actually spent time learning a language that is now in demand exclusively in my own projects. I was unable to find work locally or remotely. Now I’m moving towards php, since it simply has work.

    Therefore, if you do not live in Moscow, St. Petersburg, or are not a student at a technical university, then I would not advise you to learn Python as your first language. Pay attention to PHP - there are always places for it, there is work, there is experience. And the further path of development is already yours.

    P.S. As my friend told me, the situation is almost the same in Ruby. But here I can no longer say with certainty.