What is Python? High level programming language

Python is a high-level universal language that can be extended and integrated. He, for example, is included in the application package as a tool for writing macros. This makes Python a smart choice for many programming tasks, large and not very, and not so good for a small number of computational tasks.

Where is better to use?

Python is ideal for projects requiring rapid development. It supports several programming paradigms, which is good for programs that require flexibility. And the presence of many packages and modules provides versatility and saves time.

Guido van Rossum is the creator of Python, affectionately honored by the community with the title "a magnanimous life-long dictator." In the late 1980s, Guido liked the features of some programming languages, but not one of them possessed all the features he would like to have. In particular, the language should have the following characteristics.

python what is it

Scripting language

A script is a program that manages 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 that expressions belong to the same group using indentation. Such a group is called a code block. Other languages ​​use different syntax or punctuation. For example, in C, the symbol symbol {denotes the beginning and} is the end of a sequence of commands. Indenting is considered good practice in other languages, but Python was one of the first to enforce indentation. What does it give? Indentation makes code easier to read, and code blocks require fewer signs for their beginning and end, and punctuation marks that you can accidentally skip. All this leads to fewer errors.

High Level Data Types

Computers store data in units and zeros, but people need more complex forms, such as text. A language that supports complex data is said to support high-level data types. These types of data are easy to handle. For example, in Python, strings can be separated, combined, or uppercase, searchable, etc. High-level data types, such as lists and dictionaries that can store other data, have much more functionality. than other languages.

python language

Extensibility

An extensible programming language can be supplemented. 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 expands in several ways. The main group of programmers is working on changing and improving it, and hundreds of others write modules for specific purposes.

Interpretation

Interpreted languages ​​are executed 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 translation occurs on the fly, but writing and debugging programs is faster because there is no need to wait for the compiler to complete. They are easier to carry on different platforms.

One may argue over whether Python is an interpreted or compiled language. Although in many respects it works as interpreted, before its execution its code is compiled (as in Java), and many of its components work at full speed of the machine, as they are written in C.

Guido began writing Python during the Christmas holidays in 1989, and over the next year he developed the language based on feedback from his peers. The general public saw the result in February 1991, when it was posted on one of Usenet's newsgroups.

python programming

Python for beginners

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

In Macintosh computers, this language is preinstalled, and its version depends on the age of the OS. If you are working on Windows, you have to install Python yourself. Installation package files can be selected at python.org.

Two ways to interact

One reason for the simplicity that Python programming differs in is that it comes with tools to help develop, write, and debug programs.

In interactive mode, commands are entered one line at a time, in much the same way that 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 Python built-in modules. For beginners, it will be useful to know that interactive mode includes an extensive help system. This is a convenient way to learn the capabilities of a programming language.

The IDLE development environment includes an interactive mode 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 write multi-line code. This mode can serve:

  • sandbox for safe experiments;
  • An environment for learning Python programming
  • search and bug fix tool.

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

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

Interactive work

After starting Python, the terminal window will display information about the current version of the program, its release date, a few tips for further actions and an input prompt >>>.

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

Python interprets the input and will respond if the typed requires an answer, or the interpreter does not understand it.

The following command prints a line. Since the print location is not specified, the 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 input code after pressing the enter key, and the result appears below.

python examples

View Property Information

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 the object (or its name) and press Enter.

The result depends on the object.

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

  • >>> x = [3,2]
  • >>> x
  • [3, 2]
  • >>> print x
  • [3, 2]

For strings, the result of typing "print name" is slightly different from the result obtained for entering the name. In the first case, the value is enclosed in quotation marks, 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, module, or class instance), entering a name will provide information about the data type, name, and storage location.

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

him:

  • >>> class Message:
  • ... pass
  • ...
  • >>> Message
  • <class ___ main ___. Message at 0x58db0>
  • >>> print Message
  • __main __. Message

Lines

In Python, strings are sequences of characters. 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"

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

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

You can get part of the string using the index 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 regular strings as well as with 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 fulfillment of conditions (startswith, endswith, isalnum, isalpha, isdigit, islower, isspace, istitle, isupper);
  • merge and share (join, partition, rpartition, split, splitlines);
  • format (center, ljust, lstrip, rstring, rjust, strip, zfill, expandtabs).

python 2 7

Python: Lists

If Python strings are character-limited, then lists 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 this 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']

In this example, a list of individual characters has been created. Then an element was added to the end, the order of the elements was reversed, the elements were extracted by the position of their index, the element with the value 'U' was deleted and the elements were sorted. Removing an item from the list illustrates a situation where the remove () method needs to provide additional information, namely the value that should be removed.

In addition to methods like remove (), Python has another similar feature called a function. The only difference between a function and a method is that the former is not associated with 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 function is this. The first line begins with the keyword def, followed by the name of the function and 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 called transcribe was created that 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 transcription of 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 you need to do the inverse transformation. The object has a join () method, which combines a list by dividing each element with a string value. Since the separator is not needed, the method is used on an empty string, represented by two quotation marks ('' 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 accessible through their key, not 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 own objects, you need to define a kind of template called a class. In Python, the class operator is used for this, followed by a name and a colon. The body of the class definition contains properties and methods that will be available for all instances of objects based on this class.

Benefits

Most programming languages ​​offer convenient functions, but none of them have the combination of convenience and power that Python offers. What are these benefits? Here is 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.
  • On it, you can create large applications without having to check the running programs.
  • Python supports testing and debugging of individual modules and entire programs.

Source: https://habr.com/ru/post/K6053/


All Articles