Python programming language for beginners to read. An easy way to learn the Python programming language: does it exist?

Python Programming

Part 1. Language capabilities and basic syntax

Content Series:

Is it worth learning Python?

Python is one of the most popular modern programming languages. It is suitable for solving a variety of problems and offers the same capabilities as other programming languages: dynamism, OOP support and cross-platform. The development of Python began by Guido Van Rossum back in the mid-1990s, so by now it has been possible to get rid of standard “childhood” diseases, significantly develop the best aspects of the language and attract many programmers using Python to implement their projects.

Many programmers believe that it is necessary to learn only “classic” programming languages ​​such as Java or C++, since other languages ​​will not be able to provide the same capabilities anyway. However, recently a belief has arisen that it is advisable for a programmer to know more than one language, as this broadens his horizons, allowing him to more creatively solve problems and increasing his competitiveness in the labor market.

Learning two languages ​​like Java and C++ perfectly is quite difficult and would take a lot of time; in addition, many aspects of these languages ​​contradict each other. At the same time, Python is ideal for the role of a second language, since it is immediately absorbed thanks to the already existing knowledge of OOP, and the fact that its capabilities do not conflict, but complement the experience gained from working with another programming language.

If a programmer is just starting out in the field of software development, then Python will be an ideal “introductory” programming language. Thanks to its brevity, it will allow you to quickly master the syntax of the language, and the absence of “legacy” in the form of axioms formed over many years will help you quickly master OOP. Due to these factors, the learning curve for Python will be quite short, and the programmer will be able to move from educational examples to commercial projects.

Therefore, no matter who the reader of this article is - an experienced programmer or a beginner in the field of software development, the answer to the question, which is the title of this section, should be a resounding “yes”.

This series of articles is designed to help you successfully overcome the learning curve by providing information from the most basic principles of the language to its advanced capabilities for integration with other technologies. The first article will cover the basic features and syntax of Python. In the following, we will look at more advanced aspects of working with this popular language, in particular object-oriented programming in Python.

Python architecture

Any language, whether for programming or communication, consists of at least two parts - vocabulary and syntax. The Python language is organized in exactly the same way, providing a syntax for forming expressions that form executable programs, and a vocabulary - a set of functionality in the form of a standard library and plug-ins.

As mentioned, Python's syntax is quite concise, especially when compared to Java or C++. On the one hand, this is good, since the simpler the syntax, the easier it is to learn and the fewer mistakes you can make while using it. However, such languages ​​have a drawback - they can be used to convey the simplest information and cannot express complex structures.

This does not apply to Python, since it is a simple but simplified language. The fact is that Python is a language with a higher level of abstraction, higher, for example, than Java and C++, and allows you to convey the same amount of information in a smaller amount of source code.

Python is also a general-purpose language, so it can be used in almost any area of ​​software development (standalone, client-server, Web applications) and in any subject area. Additionally, Python integrates easily with existing components, allowing you to embed Python into applications you've already written.

Another component of Python's success is its extension modules, both standard and specific. Standard Python extension modules are well-designed and time-tested functionality to solve problems that arise in every software development project, string and text processing, interaction with the operating system, and support for Web applications. These modules are also written in Python, so they have its most important property - cross-platform, allowing you to painlessly and quickly transfer projects from one operating system to another.

If the required functionality is not in the standard Python library, you can create your own extension module for subsequent repeated use. It is worth noting here that extension modules for Python can be created not only in the Python language itself, but also using other programming languages. In this case, it is possible to more efficiently implement resource-intensive tasks, such as complex scientific calculations, but the advantage of cross-platform is lost if the extension module language is not itself cross-platform, like Python.

Python runtime

As you know, all cross-platform programming languages ​​are built on the same model: it is truly portable source code and a runtime environment, which is not portable and specific to each specific platform. This execution environment usually includes an interpreter that executes the source code, and various utilities necessary to maintain the application - a debugger, reverse assembler, etc.

The Java runtime environment also includes a compiler because the source code must be compiled into bytecode for the Java virtual machine. The Python runtime includes only an interpreter, which is also a compiler but compiles Python source code directly into machine code on the target platform.

There are currently three known runtime implementations for Python: CPython, Jython, and Python.NET. As the name suggests, the first framework is implemented in C, the second in Java, and the last in the .NET platform.

The CPython runtime is usually called simply Python, and when people talk about Python, they most often mean this implementation. This implementation consists of an interpreter and extension modules written in C, and can be used on any platform for which a standard C compiler is available. In addition, pre-compiled versions of the runtime exist for various operating systems, including various versions of Windows OS and various distributions Linux. In this and subsequent articles, CPython will be considered, unless otherwise stated separately.

The Jython runtime is a Python implementation for running the Java Virtual Machine (JVM). Any JVM version is supported, starting from version 1.2.2 (the current Java version is 1.6). Working with Jython requires an installed Java machine (Java runtime environment) and some knowledge of the Java programming language. It is not necessary to know how to write source code in Java, but you will have to deal with JAR files and Java applets, as well as documentation in JavaDOC format.

Which version of the environment to choose depends solely on the preferences of the programmer; in general, it is recommended to keep both CPython and Jython on the computer, since they do not conflict with each other, but complement each other. The CPython environment is faster because there is no intermediate layer in the form of a JVM; In addition, updated versions of Python are first released as the CPython environment. However, Jython can use any Java class as an extension module and run on any platform for which a JVM implementation exists.

Both runtime environments are released under a license compatible with the well-known GPL license, so they can be used for the development of both commercial and free software. Most Python extensions are also GPL-licensed and can be freely used in any project, but there are also commercial extensions or extensions with more stringent licenses. Therefore, when using Python in a commercial project, you need to know what restrictions exist in the extension plug-in licenses.

Getting started with Python

Before you start using Python, you need to install its execution environment - in this article this is CPython and, accordingly, the python interpreter. There are various installation methods: experienced users can compile Python themselves from its publicly available source code, they can also download ready-made executable files for a specific operating system from the Web site www.python.org, and finally, many Linux distributions come with a pre-installed Python interpreter. This article uses the Windows version of Python 2.x, but the examples presented can be run on any version of Python.

After the installer has deployed the Python executables to the specified directory, you need to check the values ​​of the following system variables:

  • PATH. This variable must contain the path to the directory where Python is installed so that the operating system can find it.
  • PYTHONHOME. This variable should only contain the path to the directory where Python is installed. This directory should also contain a lib subdirectory that will be searched for standard Python modules.
  • PYTHONPATH. A variable with a list of directories containing extension modules that will be connected to Python (list elements must be separated by a system delimiter).
  • PYTHONSTARTUP. An optional variable that specifies the path to the Python script that should be executed each time an interactive Python interpreter session is started.

The command line for working with the interpreter has the following structure.

PYTHONHOME\python (options) [ -c command | script file | - ] (arguments)

Python Interactive Mode

If you start the interpreter without specifying a command or script file, it will start in interactive mode. In this mode, a special Python shell is launched into which individual commands or expressions can be entered, and their value will be immediately calculated. This is very convenient when learning Python, as you can immediately check the correctness of a particular construction.

The value of the evaluated expression is stored in a special variable called Single Underscore (_) so that it can be used in subsequent expressions. You can end an interactive session using the keyboard shortcut Ctrl–Z on Windows or Ctrl–D on Linux.

Options are optional string values ​​that can change the behavior of the interpreter during a session; their significance will be discussed in this and subsequent articles. The options specify either a specific command to be executed by the interpreter, or the path to a file that contains the script to be executed. It is worth noting that a command can consist of several expressions, separated by semicolons, and must be enclosed in quotes so that the operating system can correctly pass it to the interpreter. Arguments are those parameters that are passed for subsequent processing to the executable script; they are passed to the program as strings and separated by spaces.

To verify that Python is installed correctly and is working properly, you can run the following commands:

c:\>python-v
c:\> python –c “import time; print time.asctime()”

The -v option prints the version of the Python implementation being used and exits, while the second command prints the system time value to the screen.

You can write Python scripts in any text editor, since they are ordinary text files, but there are also special development environments designed to work with Python.

Python Syntax Basics

Python source code scripts consist of so-called logical strings, each of which in turn consists of physical lines. The # symbol is used to denote comments. The interpreter ignores comments and empty lines.

The following is a very important aspect that may seem strange to programmers learning Python as a second programming language. The fact is that in Python there is no symbol that would be responsible for separating expressions from each other in the source code, such as the semicolon (;) in C++ or Java. A semicolon allows you to separate multiple instructions if they are on the same physical line. There is also no construct such as curly braces (), which allows you to combine a group of instructions into a single block.

Physical lines are separated by the end-of-line character itself, but if the expression is too long for one line, then the two physical lines can be combined into one logical line. To do this, you need to enter a backslash character (\) at the end of the first line, and then the interpreter will interpret the next line as a continuation of the first, however, it is impossible for there to be other characters on the first line after the \ character, for example, a comment with #. Only indentation is used to highlight blocks of code. Logical lines with the same indentation size form a block, and the block ends when a logical line with a smaller indentation size appears. This is why the first line of a Python script should not be indented. Mastering these simple rules will help you avoid most of the mistakes associated with learning a new language.

There are no other radical differences in Python syntax from other programming languages. There is a standard set of operators and keywords, most of which are already familiar to programmers, while Python-specific ones will be covered in this and subsequent articles. Standard rules are also used for specifying identifiers of variables, methods and classes - the name must begin with an underscore or a Latin character of any case and cannot contain the characters @, $, %. Also, only one underscore character cannot be used as an identifier (see the footnote that talks about interactive mode of operation).

Data Types Used in Python

The data types used in Python are also the same as other languages ​​- integer and real data types; Additionally, a complex data type is supported - with a real and imaginary part (an example of such a number is 1.5J or 2j, where J is the square root of -1). Python supports strings that can be enclosed in single, double, or triple quotes, and strings, like Java, are immutable objects, i.e. cannot change their value after creation.

Python also has a logical data type bool with two value options – True and False. However, in older versions of Python there was no such data type, and furthermore, any data type could be cast to the boolean value True or False. All non-zero numbers and non-empty strings or collections of data were treated as True, and empty and zero values ​​were treated as False. This feature has been preserved in new versions of Python, however, to increase code readability, it is recommended to use the bool type for boolean variables. At the same time, if you need to maintain backward compatibility with older Python implementations, then you should use 1 (True) or 0 (False) as boolean variables.

Functionality for working with data sets

Python defines three types of collections for storing data sets:

  • tuple (tuple);
  • list(list);
  • dictionary.

A tuple is an immutable ordered sequence of data. It can contain elements of different types, such as other tuples. A tuple is defined in parentheses and its elements are separated by commas. A special built-in function, tuple(), allows you to create tuples from a given sequence of data.

A list is a mutable, ordered sequence of elements. List elements are also separated by commas, but are specified in square brackets. To create lists, the list() function is proposed.

A dictionary is a hash table that stores an element along with its identifier key. Subsequent access to elements is also performed by key, so the storage unit in a dictionary is an object-key pair and an associated value object. A dictionary is a mutable but unordered collection, so the order of elements in the dictionary can change over time. The dictionary is specified in curly braces, the key is separated from the value by a colon, and the key/value pairs themselves are separated by commas. The dict() function is available for creating dictionaries.

Listing 1 shows examples of the different collections available in Python.

Listing 1. Types of collections available in Python
('w','o','r','l','d') # tuple of five elements (2.62,) # tuple of one element [“test”,"me"] # list of two elements # empty list ( 5:'a', 6:'b', 7:'c' ) # dictionary of three elements with keys of type int

Defining Functions in Python

Although Python supports OOP, many of its features are implemented as separate functions; In addition, extension modules are most often made in the form of a library of functions. Functions are also used in classes, where they are traditionally called methods.

The syntax for defining functions in Python is extremely simple; taking into account the above requirements:

def FUNCTION_NAME(parameters): expression No. 1 expression No. 2 ...

As you can see, it is necessary to use the function word def, colon and indentation. Calling a function is also very simple:

FUNCTION_NAME(parameters)

There are just a few Python-specific things to consider. As in Java, primitive values ​​are passed by value (a copy of the parameter is passed to the function, and it cannot change the value set before the function was called), and complex object types are passed by reference (a reference is passed to the function and it may well change the object).

Parameters can be passed either simply by listing order or by name; in this case, you do not need to specify when calling those parameters for which there are default values, but pass only mandatory ones or change the order of parameters when calling a function:

#function that performs integer division - using the operator // def foo(delimoe, delitel): return delimoe // delitel print divide(50,5) # result of work: 10 print divide(delitel=5, delimoe=50) # result works: 10

A function in Python must return a value - this is done either explicitly with a return statement followed by the return value, or, in the absence of a return statement, the constant None is returned when the end of the function is reached. As you can see from the example function declarations, in Python there is no need to specify whether something is returned from a function or not, but if a function has one return statement that returns a value, then other return statements in that function must return values, and if such a value no, then you must explicitly specify return None.

If the function is very simple and consists of one line, then it can be defined right at the point of use; in Python, such a construction is called a lambda function. A lambda function is an anonymous function (without its own name), the body of which is a return statement that returns the value of some expression. This approach may be convenient in some situations, but it is worth noting that reusing such functions is impossible (“where it was born, it came in handy”).

It's also worth describing Python's attitude toward the use of recursion. By default, the recursion depth is limited to 1000 levels, and when this level is passed, an exception will be raised and the program will stop running. However, if necessary, the value of this limit can be changed.

Functions in Python have other interesting features, such as documentation and the ability to define nested functions, but these will be explored in later articles in the series with more complex examples.

Hello everyone!

Human-readable syntax, easy to learn, high-level language, Object-Oriented programming language (OOP), powerful, interactive mode, a lot of libraries. Many other advantages... And it's all in one language.
First, let's dive into the possibilities and find out what Python can do?

Why do I need your Python?

Many new programmers ask similar questions. It's like buying a phone, tell me why should I buy this phone and not this one?
Software quality
For many, including me, the main advantages are the human-readable syntax. Not many languages ​​can boast of it. Python code is easier to read, which means reusing and maintaining it is much easier than using code in other scripting languages. Python contains the most modern mechanisms for reusing program code, which is OOP.
Support Libraries
Python comes with a large number of compiled and portable functionality known as the standard library. This library provides you with a lot of features that are in demand in application programs, ranging from text search by template to network functions. Python can be extended both by your own libraries and by libraries created by other developers.
Program portability
Most Python programs run unchanged on all major platforms. Transferring program code from Linux to Windows involves simply copying program files from one machine to another. Python also gives you a lot of opportunities to create portable graphical interfaces.
Development speed
Compared to compiled or strongly typed languages ​​such as C, C++ or Java, Python increases developer productivity many times over. Python code is typically one-third or even one-fifth the size of equivalent C++ or Java code, which means less typing, less debugging time, and less maintenance effort. Additionally, Python programs run immediately without the time-consuming compilation and linking steps required in some other programming languages, further increasing programmer productivity.

Where is Python used?

  • Google uses Python in its search engine and pays Python's creator, Guido van Rossum.
  • Companies such as Intel, Cisco, Hewlett-Packard, Seagate, Qualcomm and IBM use Python for hardware testing
  • YouTube's video sharing service is largely implemented in Python
  • NSA uses Python for encryption and intelligence analysis
  • JPMorgan Chase, UBS, Getco and Citadel use Python for financial market forecasting
  • The popular BitTorrent program for exchanging files on peer-to-peer networks is written in Python
  • Google's popular App Engine web framework uses Python as its application programming language
  • NASA, Los Alamos, JPL and Fermilab use Python for scientific computing.
and other companies also use this language.

Literature

So we got to know the Python programming language better. We can say separately that the advantages of Python are that it has a lot of high-quality literature. Not every language can boast of this. For example, the JavaScript programming language cannot please users with a lot of literature, although the language is really good.

Here are sources that will help you get to know Python better, and maybe become the future Guido van Rossum.
* Some sources may be in English. This should not be surprising; now a lot of excellent literature is written in English. And for programming itself you need to know at least basic knowledge of English.

I highly recommend reading the book first - Mark Lutz. Learning Python, 4th Edition. The book has been translated into Russian, so don’t be afraid if you suddenly don’t know English. But it is the fourth edition.

For those who know English, you can read the documentation on the official Python website. Everything is described there quite clearly.

And if you prefer information from video, then I can recommend lessons from Google, taught by Nick Parlante, a student from Stanford. Six video lectures on YouTube. But there is a drop of ointment in the barrel of ointment... He conducts it in English with English subtitles. But I hope that this will stop a few.

What should I do if I read books, but don’t know how to apply the knowledge?

Don't panic!
I recommend reading the book by Mark Lutz. Python Programming (4th Edition). Previously it was “studying”, but here it is “Programming”. In “Learning” - you gain knowledge of Python, in “Programming” - Mark teaches you how to apply it in your future programs. The book is very useful. And I think one is enough for you.

I want practice!

Easily.
Above I wrote about video lectures from Nick Parlante on YouTube, but they also have some

Once upon a time, on a closed forum, I tried to teach Python. In general, things have stalled there. I felt sorry for the written lessons, and I decided to post them to the general public. So far the very first, the simplest. What happens next is more interesting, but maybe it won’t be interesting. In general, this post will be a test balloon, if you like it, I will post it further.

Python for beginners. Chapter first. "What are we talking about"

Just in case, a little boring “evangelism”. If you are tired of him, you can skip a few paragraphs.
Python (pronounced "Python" rather than "python") is a scripting language developed by Guido van Rossum as a simple language that is easy for beginners to learn.
Nowadays, Python is a widely used language that is used in many areas:
- Application software development (for example, Linux utilities yum, pirut, system-config-*, Gajim IM client and many others)
- Development of web applications (the most powerful Application server Zope and the CMS Plone developed on its basis, on which, for example, the CIA website operates, and a lot of frameworks for rapid application development Plones, Django, TurboGears and many others)
- Use as an embedded scripting language in many games, and not only (in the OpenOffice.org office suite, Blender 3d editor, Postgre DBMS)
- Use in scientific calculations (with the SciPy and numPy packages for calculations and PyPlot for drawing graphs, Python becomes almost comparable to packages like MatLab)

And this is, of course, not a complete list of projects using this wonderful language.

1. The interpreter itself, you can get it here (http://python.org/download/).
2. Development environment. It’s not necessary to begin with, and the IDLE included in the distribution is suitable for a beginner, but for serious projects you need something more serious.
For Windows I use the wonderful lightweight PyScripter (http://tinyurl.com/5jc63t), for Linux I use Komodo IDE.

Although for the first lesson, just the interactive shell of Python itself will be enough.

Just run python.exe. The input prompt will not take long to appear, it looks like this:

You can also write programs to files with the py extension in your favorite text editor, which does not add its own markup characters to the text (no Word will not work). It is also desirable that this editor be able to make “smart tabs” and not replace spaces with tabs.
To launch files for execution, you can double-click on them. If the console window closes too quickly, insert the following line at the end of the program:

Then the interpreter will wait for you to press enter at the end of the program.

Or associate py files in Far with Python and open by pressing enter.

Finally, you can use one of the many convenient IDEs for Python, which provide debugging capabilities, syntax highlighting and many other “conveniences”.

A little theory.

To begin with, Python is a strongly dynamically typed language. What does this mean?

There are languages ​​with strong typing (pascal, java, c, etc.), in which the type of a variable is determined in advance and cannot be changed, and there are languages ​​with dynamic typing (python, ruby, vb), in which the type of a variable is interpreted in depending on the assigned value.
Dynamically typed languages ​​can be divided into 2 more types. Strict ones, which do not allow implicit type conversion (Python), and loose ones, which perform implicit type conversions (for example, VB, in which you can easily add the string "123" and the number 456).
Having dealt with Python’s classification, let’s try to “play” a little with the interpreter.

>>> a = b = 1 >>> a, b (1, 1) >>> b = 2 >>> a, b (1, 2) >>> a, b = b, a >>> a , b (2, 1)

Thus, we see that assignment is carried out using the = sign. You can assign a value to several variables at once. When you specify a variable name to the interpreter interactively, it prints its value.

The next thing you need to know is how the basic algorithmic units are constructed - branches and loops. To begin with, a little help is needed. In Python there is no special delimiter for blocks of code; indentation serves their role. That is, what is written with the same indentation is one command block. At first this may seem strange, but after a little getting used to it, you realize that this “forced” measure allows you to get very readable code.
So the conditions.

The condition is specified using an if statement that ends with “:”. Alternative conditions that will be met if the first check fails are specified by the elif operator. Finally, else specifies a branch that will be executed if none of the conditions are met.
Note that after typing if, the interpreter uses the "..." prompt to indicate that it is waiting for further input. To tell him that we are finished, we must enter an empty line.

(The example with branches for some reason breaks the markup on the hub, despite the dances with the pre and code tags. Sorry for the inconvenience, I threw it here pastebin.com/f66af97ba, if someone tells me what’s wrong, I’ll be very grateful)

Cycles.

The simplest case of a loop is the while loop. It takes a condition as a parameter and is executed as long as it is true.
Here's a small example.

>>> x = 0 >>> while x<=10: ... print x ... x += 1 ... 0 1 2 ........... 10

Please note that since both print x and x+=1 are written with the same indentation, they are considered the body of the loop (remember what I said about blocks? ;-)).

The second type of loop in Python is the for loop. It is similar to the foreach loop in other languages. Its syntax is roughly as follows.

For variable in list:
teams

All values ​​from the list will be assigned to the variable in turn (in fact, there can be not only a list, but also any other iterator, but let’s not worry about that for now).

Here's a simple example. The list will be a string, which is nothing more than a list of characters.

>>> x = "Hello, Python!" >>> for char in x: ... print char ... H e l ........... !

This way we can decompose the string into characters.
What should we do if we need a loop that repeats a certain number of times? It’s very simple, the range function will come to the rescue.

At the input it takes from one to three parameters, at the output it returns a list of numbers that we can “go through” with the for operator.

Here are some examples of the use of the range function that explain the role of its parameters.

>>> range(10) >>> range(2, 12) >>> range(2, 12, 3) >>> range(12, 2, -2)

And a small example with a cycle.

>>> for x in range(10): ... print x ... 0 1 2 ..... 9

Input Output

The last thing you should know before you start using Python fully is how input-output is carried out in it.

For output, the print command is used, which prints all its arguments in human-readable form.

For console input, the raw_input(prompt) function is used, which displays a prompt and waits for user input, returning what the user entered as its value.

X = int(raw_input("Enter a number:")) print "The square of this number is ", x * x

Attention! Despite the existence of the input() function with a similar action, it is not recommended to use it in programs, since the interpreter tries to execute syntax expressions entered using it, which is a serious hole in the security of the program.

That's it for the first lesson.

Homework.

1. Create a program for calculating the hypotenuse of a right triangle. The length of the legs is requested from the user.
2. Create a program for finding the roots of a quadratic equation in general form. The coefficients are requested from the user.
3. Create a program to display a multiplication table by the number M. The table is compiled from M * a, to M * b, where M, a, b are requested from the user. The output should be carried out in a column, one example per line in the following form (for example):
5 x 4 = 20
5 x 5 = 25
And so on.

Last update: 01/24/2018

Python is a popular high-level programming language that is designed for creating various types of applications. These include web applications, games, desktop programs, and working with databases. Python has become quite widespread in the field of machine learning and artificial intelligence research.

The Python language was first announced in 1991 by Dutch developer Guido Van Rossum. Since then, this language has come a long way in development. In 2000, version 2.0 was published, and in 2008, version 3.0. Despite the seemingly large gaps between versions, subversions are constantly being released. So, the current current version at the time of writing this material is 3.7. More detailed information about all releases, versions and language changes, as well as the interpreters themselves and the necessary utilities for work and other useful information can be found on the official website https://www.python.org/.

Main features of the Python programming language:

Python is a very simple programming language; it has a concise and at the same time quite simple and understandable syntax. Accordingly, it is easy to learn, and in fact this is one of the reasons why it is one of the most popular programming languages ​​specifically for learning. In particular, in 2014 it was recognized as the most popular programming language for learning in the United States.

Python is also popular not only in the field of education, but in writing specific programs, including commercial ones. This is largely why many libraries have been written for this language that we can use.

In addition, this programming language has a very large community; on the Internet you can find a lot of useful materials and examples on this language, and get qualified help from specialists.

To create programs in Python, we need an interpreter. To install it, go to the website https://www.python.org/ and on the main page in the Downloads section we will find a link to download the latest version of the language (currently 3.7.2):

Let's follow the link to the page describing the latest version of the language. Closer to the bottom you can find a list of distributions for different operating systems. Let's select the package we need and download it. For example, in my case it is Windows 64-bit, so I select the package link Windows x86-64 executable installer. After downloading the distribution, install it.

Accordingly, for MacOS you can select macOS 64-bit installer.

On Windows OS, when you start the installer, the installation wizard window opens:

Here we can set the path where the interpreter will be installed. Let's leave it as default, that is C:\Users\[username]\AppData\Local\Programs\Python\Python36\.

In addition, at the very bottom, check the “Add Python 3.6 to PATH” checkbox to add the path to the interpreter to the environment variables.

After installation, we can find icons for accessing various Python utilities in the Start menu on Windows OS:

Here the Python 3.7 (64-bit) utility provides an interpreter in which we can run the script. In the file system, the interpreter file itself can be found along the path where the installation was carried out. On Windows this is the default path C:\Users\[username]\AppData\Local\Programs\Python\Python37, and the interpreter itself represents the file python.exe. On Linux OS, installation is carried out along the path /usr/local/bin/python3.7.

Let's move on to the theoretical and practical part and start with what an interpreter is.

Interpreter

Interpreter is a program that executes other programs. When you write a program in Python, the interpreter reads your program and executes the instructions it contains. In reality, the interpreter is a layer of program logic between your program code and your computer's hardware.

Depending on the version of Python you are using, the interpreter itself can be implemented as a C program, as a set of Java classes, or in some other form, but more on that later.

Running a script in the console

Let's run the interpreter in the console:

Now it is waiting for command input, enter the following instruction there:

Print "hello world!"

yay, our first program! :D

Running a script from a file

Create a file "test.py", with the contents:

# print "hello world" print "hello world" # print 2 to the power of 10 print 2 ** 10

and execute this file:

# python /path/to/test.py

Dynamic compilation and bytecode

After you run the script, it first compiles the script source into bytecode for the virtual machine. Compilation is simply a translation step, and bytecode is a low-level, platform-independent representation of the source text of the program. Python translates each instruction in the script source code into groups of bytecode instructions to improve program execution speed because bytecode executes much faster. After compilation into bytecode, a file is created with the extension ".pyc" next to the original script text.

The next time you run your program, the interpreter will bypass the compilation stage and produce a compiled file with the extension ".pyc" for execution. However, if you change the sources of your program, the compilation to bytecode step will occur again, since Python automatically keeps track of the modification date of the source code file.

If Python is unable to write a bytecode file, for example due to lack of write permissions to disk, then the program will not be affected, the bytecode will simply be collected in memory and removed from there when the program exits.

Python Virtual Machine (PVM)

After the compilation process goes through, the bytecode is passed to a mechanism called virtual machine, which will execute the instructions from the bytecode. Virtual machine is a runtime mechanism, it is always present in the Python system and it is an extreme component of the system called the “Python Interpreter”.

To consolidate what we have learned, let's clarify the situation once again: compilation into bytecode is done automatically, and PVM is just a part of the Python system that you installed along with the interpreter and compiler. Everything happens transparently to the programmer, and you do not have to perform these operations manually.

Performance

Programmers with experience in languages ​​such as C and C++ may notice some differences in the Python execution model. The first is that there is no build step or calling the "make" utility; Python programs can be run immediately after writing the source code. The second difference is that bytecode is not binary machine code (for example, instructions for an Intel microprocessor), it is an internal representation of a Python program.

For these reasons, programs in Python cannot execute as quickly as in C/C++. The instructions are traversed by the virtual system, not the microprocessor, and to execute the bytecode requires additional interpretation, the instructions of which take longer than the microprocessor's machine instructions.

However, on the other hand, unlike traditional interpreters, for example in PHP, there is an additional compilation stage - the interpreter does not need to analyze the source text of the program every time.

As a result, Python's performance falls between traditional compiling and traditional interpreting programming languages.

Alternative Python Implementations

What was said above about the compiler and the virtual machine is typical for the standard Python implementation, the so-called CPython (implementation in ANSI C). However, there are also alternative implementations such as Jython and IronPython, which will be discussed now.

This is the standard and original Python implementation, so named because it is written in ANSI C. This is what we installed when we selected the package ActivePython or installed from FreeBSD ports. Since this is a reference implementation, it is generally works faster, more consistently and better than alternative implementations.

Jython

Original name JPython, main purpose - tight integration with the Java programming language. The Jython implementation consists of Java classes that compile Python code into Java bytecode and then transmit the resulting bytecode Java virtual machine (JVM).

The goal of Jython is to allow Python programs to control Java applications, just as CPython can control C/C++ components. This implementation has seamless integration with Java. Because Python code is translated into Java bytecode, it behaves exactly like a real Java program at runtime. Jython programs can act as applets and servlets, create a graphical interface using Java mechanisms, etc. Moreover, Jython provides support for the ability to import and use Java classes in Python code.

However, because the Jython implementation is slower and less robust than CPython, it is of interest to Java developers who need a scripting language as an interface to Java code.

The implementation is intended to provide integration of Python programs with applications built to run on the Microsoft .NET Framework of the Windows operating system, as well as Mono, the open source equivalent for Linux. The .NET framework and the C# runtime are designed to enable interoperability between software objects—regardless of the programming language used—in the spirit of Microsoft's earlier COM model.

IronPython allows Python programs to act as both client and server components accessible from other .NET programming languages. Because the development is carried out by Microsoft, one would expect significant performance optimizations from IronPython, among other things.

Execution speed optimization tools

There are other implementations, including a dynamic compiler Psycho and the Shedskin C++ translator, which attempt to optimize the underlying execution model.

Dynamic compiler Psyco

Psyco system is a component that extends the bytecode execution model, allowing programs to run faster. Psycho is an extension PVM, which collects and uses type information to translate parts of a program's bytecode into true binary machine code, which executes much faster. This translation does not require changes to the source code or additional compilation during development.

During program execution, Psyco collects information about object types, and this information is then used to generate highly efficient machine code optimized for that type of object. The produced machine code then replaces the corresponding bytecode sections, thereby increasing execution speed.

Ideally, some sections of program code under Psyco control can run as fast as compiled C code.

Psyco provides speed increases ranging from 2 to 100 times, but typically 4 times, when using an unmodified Python interpreter. The only downside to Psyco is that it is currently only capable of generating machine code for the architecture Intel x86.

Psyco does not come standard; it must be downloaded and installed separately. There is also a project PyPy, which represents an attempt to rewrite PVM in order to optimize the code as in Psycho, project PyPy is going to absorb more of the project Psycho.

Shedskin C++ translator

Shedskin is a system that converts Python source code into C++ source code, which can then be compiled into machine code. In addition, the system implements a platform-independent approach to executing Python code.

Frozen binaries

Sometimes you need to create independent executable files from your Python programs. This is necessary rather for packaging and distribution of programs.

Fixed binaries combine programs' bytecode, PVMs, and support files needed by programs into a single package file. The result is a single executable file, such as a file with the ".exe" extension for Windows.

Today there are three main tools for creating "frozen binaries":

  • py2exe- it can create standalone programs for Windows that use the Tkinter, PMW, wxPython and PyGTK libraries to create a graphical interface, programs that use the PyGame game creation software, win32com client programs and many others;
  • PyInstaller- resembles py2exe, but also runs on Linux and UNIX and is capable of producing self-installing executables;
  • freeze- original version.

You need to download these tools separately from Python, they are free.

Fixed binaries are quite large because they contain PVM, but by modern standards they are still not unusually large. Since the Python interpreter is built directly into the fixed binaries, installing it is not a requirement to run programs on the receiving end.

Summary

That’s all for today, in the next article I’ll talk about standard data types in Python, and in subsequent articles we’ll look at each type separately, as well as functions and operators for working with these types.