Python language application. Python Programming Language: Basics, Features and Examples

Since I started teaching Python in 2011, I have found several resources that I use regularly. When I first started learning the language, I was surprised at how welcoming the Python community was. Proof of this is the huge amount of free, high-quality material available. Below I will give examples of those resources that simply would not exist without the support of the community.

1. Invent Your Own Computer Games With Python

You may already have your favorite Python book, but I encourage you to read this one. You can purchase it, read it online, or download it for free in PDF. I like the same structure of the chapters: first the problem is posed, and then there are examples of solutions to the problems with detailed explanations. The same author wrote 3 more wonderful books.

2. Skulpt

I've worked in schools where for one reason or another (usually security reasons) Python was not available. Skulpt runs Python scripts in the browser and includes several examples. The first one uses the Turtle module to display geometric shapes. I often use it to test students' knowledge.

3. Guess the number

8. Random

Python has several useful built-in functions, such as print and input. The random module, on the other hand, needs to be imported before use. It allows students to add a little unpredictability to their projects.

Import random coin = [‘heads’,’tails’] flip = random.choice(coin) print(flip)

9.Anti Gravity

I rarely use the anti gravity module. But when I have to do this, I ask the students what will happen when they import it. Usually I get many different answers, sometimes they even suggest that the real effect of weightlessness will begin - they think that Python is so powerful :) You can try it yourself and offer it to your students.

Import antigravity

10. Sabotage

The biggest challenge for me as a teacher was finding syntax errors in students' programs. Luckily, before I completely burned out from exhaustion, I came up with

As a well-designed programming language, Python is well suited for solving real-world problems that developers face every day. It is used in a wide range of applications - both as a tool for managing other software components and for implementing independent programs. In fact, the range of roles that Python can play as a multi-purpose programming language is practically unlimited: it can be used to implement

anything from websites and game programs to controlling robots and spaceships.

However, Python's uses today can be broken down into several broad categories. The next few sections describe the most common uses of Python today, as well as the tools used in each area. We will not have the opportunity to research the tools mentioned here. If any of these interest you, please visit the Python Project website for more

System Programming

Python's built-in interfaces to access operating system services make it ideal for creating portable programs and system administration utilities (sometimes called shell tools). Python programs can search for files and directories, run other programs, perform parallel computations using multiple processes and threads, and do

much more.

The Python standard library is fully compliant with POSIX standards and supports all the typical operating system tools: environment variables, files, sockets, pipes, processes, multi-threaded execution model, pattern matching using regular expressions, command line arguments, standard interfaces for accessing data streams, running shell commands, appending filenames, and more

Additionally, system interfaces in Python are designed to be portable, such as the directory tree copy script, which requires no modifications no matter what operating system it is used on. The Stackless Python system used by EVE Online also offers improved parallel processing solutions.

Graphical interface

Python's simplicity and fast development speed make it an excellent GUI development tool. Python includes a standard object-oriented interface to the Tk GUI API called tkinter (B Python 2.6 it's called Tkinter) that allows Python programs to implement a portable graphical interface with the appearance of the operating system. Python-based GUIs/

tkinter can be used without changes in MS Windows, X Window (on UNIX and Linux systems) and Mac OS (both in the classic version and in OS X). The free PMW extension package contains additional visual components for the tkinter suite. In addition, there is the wxPython GUI API, based on the C++ library, which offers an alternative set of tools for building portable GUIs in Python.

High-level tools such as PythonCard and Dabot are built on top of APIs such as wxPython and tkinter. By choosing the appropriate library, you will also be able to use other GUI tools such as Qt (using PyQt), GTK (using PyGtk), MFC (using PyWin32), .NET (using IronPython), Swing (using Jython - the implementation of the Python language in Java, which is described in Chapter 2, or JPype). To develop web-based applications or applications that do not have high UI requirements, you can use Jython, Python web frameworks, and CGI scripts, which are described in the next section and provide additional capabilities for creating a user interface.

Web scripts

The Python interpreter comes with standard Internet modules that allow programs to perform a variety of network operations in both client and server mode. Scripts can interact over sockets, extract information from forms sent to server-side CGI scripts; transfer files via FTP; process XML files; transmit, receive, create and parse

emails; load web pages from specified URLs; parse HTML and XML markup of received web pages; carry out interactions using XML-RPC, SOAP and Telnet protocols and much more.

The libraries included with Python make implementing such tasks surprisingly easy.

Additionally, there is a huge collection of third-party tools for creating network programs in Python that can be found on the Internet. For example, the HTMLGen system allows you to create HTML pages based on Python class definitions. The mod_python package is designed to run Python scripts under the Apache web server and supports Python Server Pages engine templates. The Jython system provides

seamless Python/Java integration and supports server-side applets that run on the client side.

In addition, there are full-fledged web development packages for Python such as Django, TurboGears, web2py, Pylons, Zope, and WebWare that support the ability to quickly create fully functional, high-quality websites in Python. Many of them include features such as object-relational mappings, Model/View/Controller architecture, server-side scripting, template support, and AJAX technologies, providing

Complete and reliable solutions for web application development.

Component Integration

The ability to integrate software components into a single application using Python was already discussed above when we talked about Python as a control language. Python's ability to extend and integrate into

systems in C and C++ makes it a convenient and flexible language for describing the behavior of other systems and components. For example, integration with a C library allows Python to check for and run library components, and embedding Python into software products allows software products to be customized without having to rebuild the products or ship them with source code.

Tools like Swing and SIP, which auto-generate code, can automate the steps of linking compiled components in Python for later use in scripts, and the Cython system allows programmers to mix Python and C code. Huge Python platforms like support COM

on MS Windows, Jython - a Java implementation, IronPython - a .NET implementation, and various CORBA implementations provide alternative ways to organize interactions with software components. For example, on the Windows operating system, Python scripts can use application control platforms such as MS Word and Excel.

Database Applications

Python has interfaces for accessing all major relational databases - Sybase, Oracle, Informix, ODBC, MySQL, PostgreSQL, SQLite and many others. In the Python world, there is also a portable database API for accessing SQL databases from Python scripts that unifies access to different databases. For example, when using a portable API, a script designed to work with a free MySQL database can work with other database systems (such as Oracle) with virtually no modifications. All you have to do to do this is replace the low-level interface used.

The standard pickle module implements a simple object storage system that allows programs to save and restore Python objects in files or specialized objects. You can also find a third-party system on the Internet called ZODB.

It is a completely object-oriented database

for use in Python scripts. There are also

tools such as SQLObject and SQLAlchemy that display

relational tables into the Python class model. Since Python 2.5,

The SQLite database has become a standard part of Python.

Rapid prototyping

In Python programs, components written in Python and C look the same. This allows you to first prototype systems in Python and then port selected components to compiling languages ​​such as C and C++. Unlike some other prototyping tools, Python does not require that the system be completely rewritten once the prototype is debugged. Parts of the system that do not require the execution efficiency that C++ provides can be

leave it in Python, which will significantly simplify the maintenance and use of such a system.

Math programming

and scientific computing

The NumPy math extension mentioned above includes powerful elements such as array objects, interfaces to standard math libraries, and much more. Extending NumPy—by integrating with math libraries written in compiling programming languages—turns Python into a complex but convenient mathematical programming tool that can often replace existing code written in traditional compiling languages ​​such as FORTRAN and C++.

Additional math tools for Python support the ability to create animation effects and 3D objects, allow you to organize parallel calculations, and so on. For example, the popular SciPy and ScientificPython extensions provide additional libraries for scientific computing and take advantage of the NumPy extension capabilities.

Games, images, artificial intelligence,

XML robots and much more

The Python programming language can be used to solve a wider range of problems than can be mentioned here. For example:

Create game programs and animation videos using

pygame systems

Exchange data with other computers via serial

port using the PySerial extension

Process images using PIL, PyOpenGL extensions,

Blender, Maya and others

Control the robot using the PyRo tool

Parse XML documents using the xml package, xmlrp- module

clib and third party extensions

Program artificial intelligence using a neuro-emulator

networks and expert system shells

Analyze natural language phrases using the NLTK package.

You can even play solitaire using PySol. Support for many other application areas can be found on the PyPI website or by using search engines (search for links using Google or http://www.python.org).

Generally speaking, many of these uses of Python are just variations of the same role called component integration. Using Python as an interface to component libraries written in C makes it possible to write Python scripts to solve problems in a wide variety of application areas. As a general-purpose, multi-purpose programming language that supports integration, Python can be used very widely.

By the way, are you having problems with your laptop's power supply? We advise you to buy laptop power supplies at very affordable prices. On the company's website darrom.com.ua you will find power supplies for any laptop.

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 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 Python's 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 designed 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.

Psyco Dynamic Compiler

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 the program code under the control of Psyco 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.

Python 3 is a modern language that makes it easy and enjoyable to write programs.

To print values, Python has the print() function. Inside the parentheses, separated by commas, we write what we want to output. Here's a program that does a few calculations:

Print(5 + 10) print(3 * 7, (17 - 2) * 8) print(2 ** 16) # two asterisks mean exponentiation print(37 / 3) # one slash means division with a fraction answer print(37 // 3) # two slashes calculate the quotient of a whole division # this is like the div operation in other languages ​​print(37 % 3) # the percentage calculates the remainder of a whole division # this is like the mod operation in other languages

To enter data into the program, we use the input() function. It reads one line.

Here is a program that reads the username and greets him:

Peter print("What is your name?") name = input() # read the string and put it in the variable name print("Hello, " + name + "!")

We will write programs that read data, process it and output some result. When run on a computer, such programs read data that the user enters from the keyboard and display the result on the screen.

Let's try to write a program that reads two numbers and displays their sum. To do this, we count two numbers and store them in variables a and b, using the assignment operator =. To the left of the assignment operator in Python programs is the name of the variable - for example, a string of Latin letters. Any expression can be placed to the right of the assignment operator. The name will indicate the result of evaluating the expression. Play this program and look at the results:

5 7 a = input() b = input() s = a + b print(s)

We see that the program outputs 57, although in real life 5 + 7 would be 12. This happened because Python in the third line “added” two strings, not two numbers. In Python, two lines are added like this: the second line is added to the first line.

Note that in the visualizer, the contents of variables a and b are enclosed in quotes. This means that a and b contain strings, not numbers.

In Python, all data is called an object. The number 2 is represented by the object "number 2", the string "hello" is the object "string "hello" ".

Every object belongs to some type. Strings are stored in objects of type str , integers are stored in objects of type int , fractional numbers (real numbers) are stored in objects of type float . The type of an object determines what actions can be done with objects of that type. For example, if the variables first and second contain objects of type int , then they can be multiplied, but if they contain objects of type str , then they cannot be multiplied:

First = 5 second = 7 print(first * second) first = "5" second = "7" print(first * second)

To convert a string of numbers to an integer, we'll use the int() function. For example, int("23") will return the number 23 .

Here is an example of a correct program that reads two numbers and prints their sum:

5 7 a = int(input()) b = int(input()) s = a + b print(s)

  • Goal 1- help with links, materials, for those who are planning to study programming and take Python as their first language. Show that it is not as difficult as it seems.
  • Goal 2- collect links to useful and interesting materials on this topic in the comments.

0. Will I succeed?

From the very beginning I doubted that I would be able to do anything more than Hello World. It seemed to me that programming was extremely difficult and extremely magical. In addition, there is work, hobbies, family, which will distract from full study.

I shouldn't have been afraid and I don't recommend it to you. Programming will probably never become my main profession, but it is a great way to be creative. This is chess and Civilization in one bottle.

Everything is simpler than it seems and much more interesting.

1. Literature

Mark Lutz “Python Programming”- it is recommended to read it on many forums and courses. It seemed to me too detailed and loaded for a beginner. Read a lot, program a little. It is much more useful to read it after mastering Python at least.

Mark Summerfield “Python 3 Programming”- dynamically, with excellent examples and tasks. Without unnecessary in-depth, which only complicates everything at the beginning. I recommend starting with this book; it will help you quickly understand without intimidating you with difficulties.

All other books turned out to be less useful and informative. In general, it is difficult to just pick up good literature on this topic and buy it in a store or in a digital version.

2. What to read on the Internet

http://pythonworld.ru/ - talks about the basics of the language in simple and understandable language, often used as a cheat sheet.

After another two months, I was able to create my first Django application. But the main thing is that now I have enough knowledge for independent development and learning. The hardest thing is to get to this point.

Another month later, I joined two projects on GitHub and am participating in them. Of course, I still solve simple problems, but in return I receive advice and training.

Tags: python training, programming training