/ / Python - what is it? High Level Programming Language

Python - what is it? High Level Programming Language

Python is the universal language of highlevel that can be expanded and embedded. For example, it is included in the application package as a macro writing tool. This makes Python a smart choice for many programming tasks, large and small, and less successful for a small number of computational tasks.

Where better to use?

Python is perfect for projectsrequiring quick development. It supports several programming paradigms, which is good for programs that require flexibility. And the presence of multiple packages and modules provides versatility and saves time.

Guido van Rossum - creator of Python, affectionatelycommunity honored as the “generous lifelong dictator”. In the late 1980s, Guido liked the features of some programming languages, but none of them had all the features that he wanted to have. In particular, the language should have the following characteristics.

python what is it

Scripting language

The script is a program thatmanages other programs. Scripting languages ​​are suitable for rapid development and prototyping, because they do a good job of transferring data from one component to another and save the programmer from such troublesome things as memory management.

The user community prefers to call Python a dynamic programming language.

Indent for grouping statements

Python determines whether expressions belong toone group with indents. Such a group is called a code block. Other languages ​​use different syntax or punctuation for this. For example, in C, the symbol {denotes the beginning and} is the end of a sequence of commands. Indenting is considered good practice in other languages, but one of the first to enforce indenting is to force Python. What does this give? Indenting makes the code more readable, and code blocks require less marks for their beginning and end, and punctuation marks that can be accidentally skipped. All this leads to fewer errors.

High Level Data Types

Computers store data in ones and zeros, butpeople need more complex forms, such as text. A language supporting complex data is said to support high-level data types. These types of data are easy to operate. For example, in Python, strings can be split, merged, translated into upper or lower case, they can be searched, etc. High-level data types, such as lists and dictionaries, which can store other data, have much greater functionality, than other languages.

python language

Extensibility

Extensible programming language can beadded Such languages ​​are very powerful because add-ons make them suitable for many applications and operating systems. Extensions can add data types or concepts, modules and plugins. The Python language is extended in several ways. The core group of programmers is working on changing and improving it, while hundreds of others are writing modules for specific purposes.

Interpretation

Интерпретируемые языки выполняются directly from source code written by people, and programs written in compiled languages, such as C ++, must be translated into machine code. Interpreted languages ​​are slower because the translation happens on the fly, but writing programs and debugging them is faster because there is no need to wait for the compiler to finish. They are easier transferred to different platforms.

You can argue about whether Pythoninterpretable or compiled language. Although in many ways it works as interpreted, its code is compiled (as in Java) before execution, and many of its components run at full speed of the machine, as they are written in C.

Guido began writing Python during the Christmasvacation in 1989, and over the next year he was refining the language based on feedback from his colleagues. The general public saw the result in February 1991, when it was posted to one of the Usenet newsgroups.

python programming

Python for beginners

In order to start writing programs in Python,need to install it. Versions of Python 2.7 and Python 3.5 have significant differences, due to which the programs written on them are incompatible.

In Mac computers, this languagepreinstalled, and its version depends on the age of the OS. When working in Windows, you will have to install Python yourself. The installation package files can be selected on the python.org website.

Two ways to interact

One of the reasons for simplicity, which is different programming in Python, is that it comes with tools that will help develop, write and debug programs.

In interactive mode, commands are entered one by one.line at a time, almost the same as the operating system (shell) accepts commands from the command line. You can also create short multi-line programs or import code from text files or built-in Python modules. For beginners, it will be helpful to know that the interactive mode includes an extensive help system. This is a convenient way to learn the possibilities of a programming language.

IDLE development environment includes an interactivemode and tools for writing and running programs, as well as a name tracking system. The environment is written in Python and demonstrates the extensive features of the language.

python for beginners

Interactive mode

Here you can do almost everything that can be done in the program, even writing multi-line code. This mode can serve:

  • sandbox for safe experiments;
  • an environment that allows learning programming in Python;
  • error search and fix tool.

Please note that it is not possible to save entered online. To do this, write a copy of the code and the results in the file.

Interactive mode can be used ascalculator, manipulate text and assign values ​​to variables. You can also import modules, functions, or parts of programs to test them. It helps to experiment with Python objects without writing long programs and debug programs by importing their parts one at a time.

Work online

After starting Python, the terminal window displays information about the current version of the program, the date of its release, several tips for further actions and an invitation to enter >>>.

To work in interactive mode, enter a command or expression and press the enter key.

Python interprets the input and responds if the typed one requires a response, or the interpreter does not understand it.

The following command will print a string. Since the print location is not specified, output occurs on the screen.

  • >>> print "Hello world!"
  • Hello World!

This single line is the whole program! In interactive mode, Python processes each line of the entered code after pressing the enter key, and the result appears below.

python examples

View information about the object

In interactive mode, there are two ways to view information about an object:

  • enter the object (or its name) and press the enter key;
  • Enter the print command and object (or its name) and press Enter.

The result depends on the object.

When using some data types (integer and lists, for example), these two methods give the same result:

  • >>> x = [3.2]
  • >>> x
  • skid
  • >>> print x
  • skid

For strings, the result of typing the “print name” command is slightly different from the result obtained for entering the name. In the first case, the value is in quotes, and in the second - not:

  • >>> x = "MyString"
  • >>> x
  • "MyString"
  • >>> print x
  • Mystring

When a name refers to a block of code (for example, a function, a module, or an instance of a class), entering a name will provide information about the type of data, name, and storage location.

The following example creates a class named Message and displays information about

him:

  • >>> class Message:
  • ... pass
  • ...
  • >>> Message
  • >>> print Message
  • __main __. Message

Strings

In Python, strings are sequencescharacters. A string literal is created by enclosing characters in single ("), double (") or triple ("" "or" "") quotes. In the above example, the value of the variable x is assigned:

  • >>> x = "MyString"

Python string has several inlineopportunities. One of them is the ability to return your copy with all lowercase letters. These features are known as methods. To invoke an object method, use dotted syntax. That is, after entering the name of the variable, which in this case is a reference to the object of the string, you need to put an operator-dot (.), And then the name of the method followed by opening and closing the bracket:

  • >>> x.lower ()
  • "mystring"

You can get part of a string using the indexing operator s [i]. Indexing starts from zero, so s [0] returns the first character in the string, s [1] returns the second, and so on:

  • >>> x [0]
  • "m"
  • >>> x [1]
  • "y"

String methods work with both regular strings and Unicode. They perform the following actions:

  • case change (capitalize, upper, lower, swapcase, title);
  • counting;
  • encoding change (encode, decode);
  • search and replace (find, replace, rfind, index, rindex, translate);
  • check the conditions (startswith, endswith, isalnum, isalpha, isdigit, islower, isspace, istitle, isupper);
  • combine and split (join, partition, rpartition, split, splitlines);
  • format (center, ljust, lstrip, rstring, rjust, strip, zfill, expandtabs).

python 2 7

Python lists

If Python strings are limited to characters, thenLists have no restrictions. They are ordered sequences of arbitrary objects, including other lists. In addition, you can add, delete and replace their elements. A series of objects, separated by commas inside square brackets, is the Python list. What it is is shown below - here are examples of data and operations with them:

  • >>> bases = ["A", "C", "G", "T"]
  • >>> bases
  • ["A", "C", "G", "T"]
  • >>> bases.append ("U")
  • >>> bases
  • ["A", "C", "G", "T", "U"]
  • >>> bases.reverse ()
  • >>> bases
  • ["U", "T", "G", "C", "A"]
  • >>> bases [0]
  • "U"
  • >>> bases [1]
  • "T"
  • >>> bases.remove ("U")
  • >>> bases
  • ["T", "G", "C", "A"]
  • >>> bases.sort ()
  • >>> bases
  • ["A", "C", "G", "T"]

This example has created a list of individualcharacters. Then an element was added to the end, the order of the elements was reversed, elements were extracted according to the position of their index, an element with a value of "U" was removed, and elements were sorted. Removing an item from the list illustrates the situation when the remove () method needs to provide additional information, namely the value that should be removed.

In addition to methods like remove (), Pythonhas another similar feature called a function. The only difference between a function and a method is that the first is not related to a specific object.

Python: functions

Functions perform actions on one or more values ​​and return a result. A large number of them are built into Python. Examples of built-in functions:

  • len () - returns the number of elements in the sequence;
  • dir () - returns a list of strings representing the attributes of an object;
  • list () - returns a new list initialized from some other sequence.
  • >>> help (round)
  • Help on built-in function round:
  • round (...)
  • round (number [, ndigits]) -> floating point number

It is also possible to define your own functions.

python functions

User Defined Functions

The process of creating your own Python functions like this.The first line starts with the keyword def, followed by the name of the function and the arguments (expected input values) enclosed in brackets, and ends with a colon. Subsequent commands make up the body of the function and must be indented. If the comment is at the beginning of the function body, it becomes part of its documentation. The last line of the function returns the result:

  • >>> def transcribe (dna):
  • ... "" "Return dna string as rna string." ""
  • ... return dna.replace ("T", "U")
  • ...
  • >>> transcribe ("CCGGAAGAGCTTACTTAG")
  • "CCGGAAGAGCUUACUUAG"

In this example, a function has been created calledtranscribe, which expects a string representing the DNA sequence. The replace () method returns a copy of the original string, replacing all occurrences of one character with another. Three lines of code allowed transcribing DNA into RNA. The inverse function looks like this:

  • >>> def reverse (s):
  • ... "" "Return the sequence string in reverse order." ""
  • ... letters = list (s)
  • ... letters.reverse ()
  • ... return "" .join (letters)
  • ...
  • >>> reverse ("CCGGAAGAGCTTACTTAG")
  • "GATTCATTCGAGAAGGCC"

The reverse function takes a string, creates a list,based on it, and changes its order. Now we need to do the inverse transform. The object has a join () method that combines a list, dividing each element by the value of a string. Since no separator is needed, the method is used on an empty string represented by two quotes ("" or "").

Dictionaries

What is a Python dictionary?It has the same advantages as a regular paper dictionary. Allows you to quickly find the desired value (definition) associated with the key (word). Dictionaries are enclosed in braces and contain a comma-separated sequence of key-value pairs. Dictionaries are not ordered. Instead, dictionary meanings are available through their key, rather than their position.

  • >>> basecomplement = {"A": "T", "C": "G", "T": "A", "G": "C"}
  • >>> basecomplement.keys ()
  • ["A", "C", "T", "G"]
  • >>> basecomplement.values ​​()
  • ["T", "G", "A", "C"]
  • >>> basecomplement ["A"]
  • "T"

Classes

In order to create your ownobjects, you need to define a kind of pattern, called a class. In Python, the class statement followed by the name and a colon is used for this. The body of the class definition contains properties and methods that will be accessible to all instances of objects based on this class.

Benefits

Большинство языков программирования предлагают convenient features, but none of them have the combination of convenience and power that Python offers. What are these benefits? Here are some of them:

  • The language can be embedded in other applications and used to create macros. For example, in Paint Shop Pro 8 and later, it is a scripting language.
  • Python is free to use and distribute, commercially or not.
  • The language has powerful capabilities for processing and searching for text, which is used in applications that work with a large amount of textual information.
  • You can create large applications on it without having to check the programs that are running.
  • Python supports testing and debugging of individual modules and entire programs.