A simple language about programming in python 3. The Python programming language for beginners. Flow Control Instructions - if, for, while

A couple of decades ago, programmers seemed to be some kind of shamans who knew what was not available to others. Sometimes people learned programming on their knees, writing code on a piece of paper, because the "concentration of computer devices per capita" was extremely low. Now, it is difficult to find a person who does not have a desktop computer or laptop at home. Educational technologies also do not stand still.

A bit of history

The Python programming language was developed by Guido van Rossum in the late eighties. Guido was at that time an employee of the Dutch CWI Institute. He wrote this language in his spare time, putting in there some ideas about the ABC language, which he contributed to.

The language was not named in honor of the reptile. In fact, the idea for the name was a popular British comedy show of the seventies called "Monty Python's Flying Circus", although Python is still much more often compared to a snake, as even the emblem on the official website (it shows two snake heads) shows.

It's not just van Rossum's design intuition that is credited as the reason why the Python programming language is so popular. Learning from scratch becomes a pleasant and easy experience, given the presence of a friendly user community.

Not so long ago, in 2008, the first version of Python 3000 (3.0), which had been tested for a long time, was released, where many architectural flaws were eliminated. At the same time, the developers tried to maintain compatibility with previous versions of the language. Although there is a more recent version, both branches (2.x and 3.x) are supported.

Concise programming language

Python has a number of advantages over other languages. It is understandable almost intuitively, has a "transparent" syntax. This means that the program code in this language is much easier to read, which reduces the time not only for writing it, but also for various improvements and checks.

Of course, the "old school" programmer will say that you definitely need to know several languages, or you can even start by learning machine code. But, after completing a programming course in the Python language, a person will receive not only specific knowledge, but also the opportunity to realize their creative nature by creating applications and programs that are useful for themselves. Perhaps soon programming will be as necessary as knowledge of a foreign language.

Lack of self-esteem

It is worth discarding the misconception that programming is hard. No, programming is much more interesting than it looks; other activities and the so-called "lack of time" or laziness can interfere.

Basic literature will help you quickly learn programming in the Python language. The training course should begin by reading two books from which you can learn the basics. The first one is "Python Programming" by Mark Lutz and the second one is "Python 3 Programming" by Mark Summerfield. Lutz's book describes in detail, sometimes even too much, all the basic principles on which the language is built. Some advise reading Mark Lutz not for mastering, but for deepening basic knowledge. Summerfield's book explains everything more concisely, the author does not frighten the reader with any difficulties. There is other literature, but these textbooks are the most useful and informative.

introductory course

Let's think back to elementary school. As a rule, even a child comes to the first grade with some minimal knowledge: parents studied with someone, someone went to the "zero". The same goes for learning the Python programming language. It is really convenient and "transparent", but without a minimum knowledge of the basic principles of the programs, training will be difficult. It's like learning music without hearing the music. Therefore, those who have never encountered programming at all should familiarize themselves with the "introductory minimum".

The CS50 lectures will be a useful help. This is a Harvard University course on Java Script programming, but the first lectures explain the interaction between a computer and programs in general in an accessible and understandable way. A Russian-speaking user has access to video recordings of this course with translation, additional materials, text versions of lectures and practical tasks. Videos can be found almost anywhere, like YouTube, but the entire content is on the Java Script site.

In the Internet

The Python programming language is gaining popularity, so for a long time there have been several portals with a lot of self-learning materials. For example, "Python 3 for Beginners". This site has a lot of materials for beginners, it can be used as a cheat sheet. There is also a large amount of information on this topic with free access on the Codecademy website.

Forum communication is important. Learning alone is always harder, so don't neglect different communities.

Paid courses

You can always use paid courses, but sometimes it costs a lot of money, and the result may be unsatisfactory. Therefore, of course, it is advisable to choose courses that offer a free introductory task. For example, there is an intensive on the topic "Python Programming Fundamentals" on GeekBrains. The class is free and takes place every 10 days. To register, you must log in to the site.

Tip: Whatever course you choose, get to know the basics of the language first so you don't waste time on something you can easily pick up on your own. It will be enough to read the above books.

Of course, when the theory is mastered, I want to practice. The lectures of Nick Parlante must be mentioned here. They are in English, although in general there is a lot of good educational literature in English, and this should not be surprising. In lectures, Nick not only teaches the Python programming language, but also gives excellent practical tasks.

Usage

The Python programming language has been used to create many applications that many people use on a daily basis. For example, this is the sixth version of the BitTorrent torrent client. Also "Python" ("Pyton") is used in the bitmap graphics editor Gimp. With it, additional modules, filters, for example, are created. Much of Civilization IV and Batterfield 2 are written in this language.

Python is used by companies such as Google, Facebook, Instagram, Dropbox, Pinterest. It also works in the core of the Yandex Disk application. About 10% of the company's employees write in Python, and many programmers call it their favorite language.

How to get started

No code can work "in the air", the Python programming language also obeys this rule. Learning from scratch, although it begins with theory, in fact, one can say, it begins with the installation of a working environment on a personal computer. How to do it? It's simple: you need to follow the link of the official Python website, download and run the installer, and then carefully follow the steps suggested by it.

Please note that you need to download a file suitable for the operating system installed on your computer!

If the installation was successful, open the console (usually, this can be done with the keyboard shortcut "ctrl + alt + T"). Now you can write your first program. For example, enter "python3". If the console displayed a "greeting" where the version of the program is indicated (for example, 3.4.0), then everything is in order, if not, then you need to install the third version of "Python" with the command: "sudo apt-get install python3".
However, this is not required. You can write code in any convenient text editor, and then run it through the console, or you can use the IDLE development environment that comes with the distribution.

Start IDLE. It only takes one line of code to create a tiny program.

print("Hello world!")

Type this code into the IDLE window and hit enter. The environment will instantly respond with an action - it will display the required text on the screen. The first program is ready.

Programming in Python

Part 1. Language Features 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 features as other programming languages: dynamism, support for OOP and cross-platform. Python development was started by Guido Van Rossum back in the mid-1990s, so by now it has managed to get rid of the standard "childhood" diseases, significantly develop the best aspects of the language and attract many programmers who use Python to implement their projects.

Many programmers feel that it is necessary to learn only "classic" programming languages ​​such as Java or C++, as other languages ​​will not provide the same capabilities anyway. However, recently there has been a belief that it is desirable for a programmer to know more than one language, as this broadens his horizons, allowing him to solve tasks more creatively and increase his competitiveness in the labor market.

Learning two languages ​​such as Java and C++ to perfection is quite difficult and would take a lot of time; moreover, many aspects of these languages ​​contradict each other. At the same time, Python is ideal for the role of a second language, as it is immediately assimilated due to the already existing knowledge in OOP, and the fact that its capabilities do not conflict, but complement the experience gained while 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. Due to its conciseness, it will allow you to quickly master the syntax of the language, and the absence of a “legacy” in the form of axioms that have been formed over the years will help you quickly master OOP. Because of these factors, Python's learning curve will be fairly short, and the programmer will be able to move from case studies to commercial projects.

Therefore, whether the reader of this article is an experienced programmer or a beginner in the field of software development, the answer to the question that 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 consistently providing information from the most basic principles of the language to its advanced capabilities in terms of integration with other technologies. In the first article, we will talk about the main features and syntax of Python. In the future, we will look at more complex 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 the same way, providing a syntax for generating expressions that form executable programs, and a dictionary, a set of functionality in the form of a standard library and plug-ins.

As already mentioned, Python's syntax is quite concise, especially when compared to Java or C++. On the one hand, this is good, because the simpler the syntax, the easier it is to learn and the fewer mistakes you can make in the process of 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, as 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 transfer the same amount of information in a smaller amount of source code.

Also, Python is 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. In addition, Python easily integrates with existing components, which makes it possible to embed Python in already written applications.

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

If the necessary functionality was not in the Python standard library, then you can create your own extension module for its subsequent repeated use. It is worth noting here that extension modules for Python can be created not only in Python itself, but also using other programming languages. In this case, it becomes 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 according to the same model: this is a truly portable source code and a runtime environment, which is not portable and specific to each specific platform. This runtime usually includes an interpreter that executes the source code and various utilities needed to maintain the application - a debugger, reverse assembler, and so on.

The Java Runtime Environment additionally 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 to the native code of the target platform.

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

The CPython runtime is usually referred to simply as Python, and when people talk about Python, this implementation is most often referred to. 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, there are already compiled versions of the runtime for various operating systems, including various versions of OC Windows and various distributions linux. In this and subsequent articles, CPython will be considered, unless otherwise specified separately.

The Jython runtime is a Python implementation for working with the Java Virtual Machine (JVM). Any version of the JVM is supported, starting with version 1.2.2 (the current version of Java is 1.6). Jython requires an installed Java machine (Java runtime environment) and some knowledge of the Java programming language. You don't need to know how to write Java source code, but you will need to be familiar 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 a 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 runtimes are released under a license compatible with the well-known GPL, so they can be used to develop both commercial and free software. Most Python extension modules are also released under the GPL license and can be freely used in any project, but there are commercial extensions or extensions with more stringent licenses. Therefore, when using Python in a commercial project, you need to be aware of what restrictions exist in the extension's plug-in licenses.

Getting started with Python

Before you can start using Python, you need to install its runtime environment - in this article it is CPython and, accordingly, the python interpreter. There are various installation methods: advanced users can compile Python themselves from its public source code, you can also download ready-made executable files for a specific operating system from the www.python.org website, and finally, many Linux distributions come with a Python interpreter already preinstalled. This article uses the Windows version of Python 2.x, but the examples provided 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 (the elements of the list must be separated by a system separator).
  • PYTHONSTARTUP . An optional variable that defines the path to a 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 run in interactive mode. In this mode, a special Python shell is launched into which you can enter individual commands or expressions, 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 named Single Underscore (_) so that it can be used in subsequent expressions. You can end an interactive session by pressing 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 are followed by either a single command that the interpreter should execute, or the path to a file that contains a script to execute. It is worth noting that a command can consist of several expressions, separated by semicolons, and must be enclosed in quotation marks so that the operating system can correctly pass it to the interpreter. Arguments are those parameters that are passed for further processing to the executable script; they are passed to the program as strings and separated by spaces.

You can run the following commands to verify that Python is properly installed and working:

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

The -v option displays 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, as they are plain text files, but there are 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 strings. The # symbol is used to denote comments. Comments and empty lines are ignored by the interpreter.

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

Physical strings are separated by the end-of-line character itself, but if the expression is too long for one string, then the two physical strings can be combined into one logical one. To do this, you need to enter a backslash character (\) at the end of the first line, and then the next line will be interpreted by the interpreter as a continuation of the first one, however, it is impossible for other characters to appear on the first line after the \ character, for example, a comment with #. Indentation is used to highlight blocks of code. Logical lines with the same indent size form a block, and the block ends when a logical line with a smaller indent appears. This is why the first line in 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 from other programming languages ​​in the syntax of Python. There is a standard set of operators and keywords, most of which are already familiar to programmers, but Python-specific ones will be covered in this and subsequent articles. The standard rules for setting identifiers of variables, methods and classes are also used - the name must begin with an underscore or a Latin character of any case and cannot contain @, $, %. Also, only one underscore character cannot be used as an identifier (see footnote for interactive mode).

Data types used in Python

The data types used in Python are also the same as in 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, while strings, like in Java, are immutable objects, i.e. cannot change their value after creation.

There is also a logical bool data type in Python with two value options - True and False. However, older versions of Python did not have this data type, and in addition, 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, while empty and zero values ​​were treated as False. This feature has been preserved in new versions of Python, however, to increase the readability of the code, it is recommended to use the bool type for boolean variables. At the same time, if you need to maintain backward compatibility with older implementations of Python, then you should use 1 (True) or 0 (False) as boolean variables.

Functionality for working with datasets

Python defines three types of collections for storing datasets:

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

A tuple is an immutable ordered sequence of data. It can contain elements of various types, such as other tuples. A tuple is defined in parentheses, and its elements are separated by commas. The 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. The elements of the list are also separated by commas, but are already set in square brackets. The list() function is used to create lists.

A dictionary is a hash table that stores an element along with its key identifier. Subsequent access to elements is also performed by key, so the unit of storage in a dictionary is a key object pair and an associated value object. A dictionary is a mutable but not ordered collection, so the order of the 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 various collections available in Python.

Listing 1. Collection types 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' ) # 3-element dictionary with int keys

Defining Functions in Python

Although Python supports OOP, however, many of its features are implemented as separate functions; in addition, extension modules are most often made also 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; subject to the above requirements:

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

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

FUNCTION_NAME(parameters)

There are only a few Python-specific things to consider. As in Java, primitive values ​​are passed by value (a copy of the parameter gets into 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 enumeration order or by name, in this case, when calling, you do not need to specify those parameters for which there are default values, but only pass required ones or change the order of parameters when calling the function:

#a 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, either explicitly by using a return statement followed by a return value, or, in the absence of a return statement, returning the constant None when the end of the function is reached. As you can see from the examples of function declarations, in Python it is not necessary to specify whether something is returned from a function or not, however, if a function has one return statement that returns a value, then other return statements in this function must return values, and if there is such a value no, you must explicitly write return None.

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

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

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

O Python(it's better to say "python", although some say "python") - the subject of this study, the creator of this programming language, the Dutchman Guido van Rossum, best says:

"Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Built-in high-level data structures, combined with dynamic typing and binding make the language attractive for rapid application development (RAD, Rapid Application Development). In addition, it can be used as a scripting language for linking software components. Python's syntax is easy to learn and emphasizes code readability, which reduces the cost of maintaining software products. Python supports modules and packages, encouraging modularity and code reuse. The Python interpreter and large standard library are available free of charge as source and executable code for all major platforms and are free to redistribute."

In the process of studying the meaning of this definition will be revealed, but for now it is enough to know that Python is a universal programming language. It has its advantages and disadvantages, as well as areas of application. Python comes with an extensive standard library for a wide range of tasks. Quality libraries for Python are available on the Internet in various subject areas: word processing tools and Internet technologies, image processing, tools for creating applications, database access mechanisms, scientific computing packages, GUI building libraries, etc. In addition, Python has fairly simple means for integrating with C, C++ (and Java) both by embedding the interpreter into programs in these languages, and vice versa, by using libraries written in these languages ​​in Python programs. The Python language supports several paradigms programming: imperative (procedural, structural, modular approaches), object-oriented and functional programming.

We can consider that Python is a whole technology for creating software products (and their prototypes). It is available on almost all modern platforms (both 32-bit and 64-bit) with a C compiler and on the Java platform.

It may seem that there is no place in the software industry for anything other than C/C++, Java, Visual Basic, C#. However, it is not. Perhaps thanks to this course of lectures and practical exercises, Python will have new adherents for whom it will become an indispensable tool.

How to describe language?

It is not the intention of this lecture to describe Python systematically: there is an original reference manual for that. Here it is proposed to consider the language simultaneously in several aspects, which is achieved by a set of examples that will allow you to quickly join real programming than in the case of a strict academic approach.

However, it is worth paying attention to the correct approach to describing the language. The creation of a program is always a communication in which the programmer conveys to the computer the information necessary for the latter to perform actions. The way the programmer understands these actions (that is, the "meaning") can be called semantics. The means of conveying this meaning is syntax programming language. Well, what the interpreter does based on the passed is usually called pragmatics. When writing a program, it is very important that there are no failures in this chain.

Syntax is a fully formalized part: it can be described in formal language syntax diagrams (which is what is done in the reference manuals). The expression of pragmatics is the language interpreter itself. It is he who reads the "message" written in accordance with the syntax and turns it into actions according to the algorithm embedded in it. Only semantics remains an informal component. It is in the translation of meaning into a formal description that the greatest complexity of programming lies. The syntax of the Python language has powerful features that help bring the programmer's understanding of a problem closer to its "understanding" by the interpreter. The internal structure of Python will be discussed in one of the final lectures.

History of the Python Language

Python was started by Guido van Rossum in 1991 when he was working on the Amoeba distributed operating system. He needed an extensible language that would provide support for system calls. ABC and Modula-3 were taken as a basis. He chose Python as the name after the BBC comedy series Monty Python's Flying Circus, rather than the name of the snake. Since then, Python has evolved with the support of the organizations where Guido has worked. The language is being improved especially actively at the present time, when not only a team of creators, but also a whole community of programmers from all over the world is working on it. And yet the last word on the direction of language development remains with Guido van Rossum.

This material is intended for those who are already familiar with programming and want to learn the Python programming language. It is designed to show you the features of the Python language, the syntax features and the basic principles of working with Python in 10 minutes with examples. There is no "water" here - information that is not directly related to the programming language. Let's start!

The Python programming language is distinguished by strong typing (Strong typing is distinguished by the fact that the language does not allow mixing different types in expressions and does not perform automatic implicit conversions, for example, you cannot subtract a set from a string), dynamic typing is used - all types are clarified already during program execution.

Variable declaration is optional, names are case sensitive (var and VAR are two different variables).

Python is an object-oriented language, everything in the language is an object.

Get help

Help (help) in Python is always available right in the interpreter. If you want to know how an object works, call help( ). Also a useful instruction is dir() , which shows all the methods of an object, and the property of objects .__doc__ , which will show you the docstring:

>>> help(5) Help on int object: (etc etc) >>> dir(5) ["__abs__", "__add__", ...] >>> abs.__doc__ "abs(number) -> number Return the absolute value of the argument."

Python Syntax

Python doesn't have block-ending constructs (such as a class or function declaration, for example) - blocks are defined using indentation. Increase the indent at the beginning of the block, decrease it at the end of the block. Statements that require indentation are terminated with a colon (:). If you don't have any code after the block start statement, insert a pass statement to pass the syntax check.

While rangelist == 1: pass

Single-line comments start with a pound sign (#), multi-line comments use (""") at the beginning and end of the comment.

Values ​​are assigned using an equal sign ("=") (in fact, objects are assigned names in the process).

Difference checking is performed with two equals characters ("==").

You can increase the value using the += operator and decrease it with -=, indicating the variable on the left side, and the value by which the increase / decrease will occur on the right. This works with many data types in Python, including strings.

You can assign a value to multiple variables on the same line. Examples:

>>> myvar = 3 >>> myvar += 2 >>> myvar 5 >>> myvar -= 1 >>> myvar 4 """This is a multiline comment. The following lines concatenate the two strings.""" >>> mystring = "Hello" >>> mystring += "world." >>> print mystring Hello world. # This swaps the variables in one line(!). # It doesn't violate strong typing because values ​​aren't # actually being assigned, but new objects are bound to # the old names. >>> myvar, mystring = mystring, myvar

Data Types in Python

In Python, data types such as lists (lists), tuples (tuples) and dictionaries (dictionaries) are available. Sets are also available, using the sets module in versions prior to Python 2.5 and built into the language in later versions.

Lists are similar to one-dimensional arrays. It is possible to have a list consisting of other lists.

Dictionaries are associative arrays in which data is accessed by key.

Tuples are immutable one-dimensional arrays.

"Arrays" in Python can be of any type, meaning you can combine numbers, strings, and other data types in lists/dictionaries/tuples.

The index of the first element is 0. A negative index value starts counting from the last to the first, [-1] will point to the last element.

Variables can point to functions.

>>> sample = , ("a", "tuple")] >>> mylist = ["List item 1", 2, 3.14] >>> mylist = "List item 1 again" # We"re changing the item >>> mylist[-1] = 3.21 # Here, we refer to the last item >>> mydict = ("Key 1": "Value 1", 2: 3, "pi": 3.14) >>> mydict["pi"] = 3.15 # This is how you change dictionary values ​​>>> mytuple = (1, 2, 3) >>> myfunction = len >>> print myfunction(mylist) 3

You can slice an array (list or tuple) using a colon (:). Leaving the initial value of the index blank will tell you to start at the first value, the blank value of the end of the index assumes the last element of the array. Negative indexes are counted backwards from the end of the array (-1 indicates the last element).

See examples:

>>> mylist = ["List item 1", 2, 3.14] >>> print mylist[:] ["List item 1", 2, 3.1400000000000001] >>> print mylist ["List item 1", 2] > >> print mylist[-3:-1] ["List item 1", 2] >>> print mylist # Adding a third parameter, "step" will have Python step in # N item increments, rather than 1. # E.g. , this will return the first item, then go to the third and # return that (so, items 0 and 2 in 0-indexing). >>> print mylist[::2] ["List item 1", 3.14]

Strings in Python

An apostrophe (‘) or double quotes (double quote - “) can be used to denote a string. Because of this, you can have quotes inside a string denoted with apostrophes (eg 'He said "hello.'" is a valid string).

Multiline strings are denoted using a triple apostrophe or quotation marks ("""). Python supports unicode out of the box. Python 2 uses the (u) character to denote a string containing unicode: u"This is a unicode string". Python3 all strings are unicode If in Python3 you want a sequence of bytes, which was essentially a string in previous versions, use the character (b): b"This is a byte string".

The (%) operator and a tuple are used to substitute parameter values ​​into a string. Each %s is replaced by an element from the tuple, from left to right. You can also use a dictionary to substitute named parameters:

>>>print "Name: %s\ Number: %s\ String: %s" % (myclass.name, 3, 3 * "-") Name: Poromenos Number: 3 String: --- strString = """ This is a multiline string.""" # WARNING: Watch out for the trailing s in "%(key)s". >>> print "This %(verb)s a %(noun)s." % ("noun": "test", "verb": "is") This is a test.

Flow Control Instructions - if, for, while

The if , for , and while statements are used to control the order in which the program is executed. There is no switch or case in Python, if is used instead. For is used to iterate through the elements of a list (or tuple). To get a sequence of numbers, use range( ) . Break is used to break the execution of the loop.

The syntax for this construct is:

Rangelist = range(10) >>> print rangelist for number in rangelist: # Check if number is one of # the numbers in the tuple. if number in (3, 4, 7, 9): # "Break" terminates a for without # executing the "else" clause. break else: # "Continue" starts the next iteration # of the loop. It "s rather useless here, # as it"s the last statement of the loop. continue else: # The "else" clause is optional and is # executed only if the loop didn't "break". pass # Do nothing if rangelist == 2: print "The second item (lists are 0-based) is 2 " elif rangelist == 3: print "The second item (lists are 0-based) is 3" else: print "Dunno" while rangelist == 1: pass

Functions in Python

Functions are declared using the "def" keyword. Optional arguments follow the mandatory arguments in the function declaration and are assigned a default value. When calling a function, you can pass arguments by specifying their name and value, while skipping some of the optional arguments or placing them in an order different from that declared in the function.

Functions can return a tuple and using tuple unpacking you can return multiple values.

Lambda functions are special functions that process a single argument.

Parameters are passed via a link. By adding elements to the passed list you will get an updated list outside of the function. In this case, assigning a new value to parameters inside the function will remain a local action. Because only the memory location is passed in, assigning a new object to a parameter as a variable will cause a new object to be created.

Code examples:

# Same as def funcvar(x): return x + 1 funcvar = lambda x: x + 1 >>> print funcvar(1) 2 # an_int and a_string are optional, they have default values ​​# if one is not passed (2 and "A default string", respectively). def passing_example(a_list, an_int=2, a_string="A default string"): a_list.append("A new item") an_int = 4 return a_list, an_int, a_string >>> my_list = >>> my_int = 10 >> > print passing_example(my_list, my_int) (, 4, "A default string") >>> my_list >>> my_int 10

Python classes

Python supports a limited form of multiple inheritance in classes.

Private variables and methods can be declared (by convention, this is not checked by the interpreter) using two underscores at the beginning and no more than one at the end of the name (eg: "__spam").

We can also assign arbitrary names to class instances. View examples:

Class MyClass(object): common = 10 def __init__(self): self.myvariable = 3 def myfunction(self, arg1, arg2): return self.myvariable # This is the class instantiation >>> classinstance = MyClass() >> > classinstance.myfunction(1, 2) 3 # This variable is shared by all classes. >>> classinstance2 = MyClass() >>> classinstance.common 10 >>> classinstance2.common 10 # Note how we use the class name # instead of the instance. >>> MyClass.common = 30 >>> classinstance.common 30 >>> classinstance2.common 30 # This will not update the variable on the class, # instead it will bind a new object to the old # variable name. >>> classinstance.common = 10 >>> classinstance.common 10 >>> classinstance2.common 30 >>> MyClass.common = 50 # This has not changed, because "common" is # now an instance variable. >>> classinstance.common 10 >>> classinstance2.common 50 # This class inherits from MyClass. The example # class above inherits from "object", which makes # it what"s called a "new-style class". # Multiple inheritance is declared as: # class OtherClass(MyClass1, MyClass2, MyClassN) class OtherClass(MyClass): # The "self" argument is passed automatically # and refers to the class instance, so you can set # instance variables as above, but from inside the class.def __init__(self, arg1): self.myvariable = 3 print arg1 >> > classinstance = OtherClass("hello") hello >>> classinstance.myfunction(1, 2) 3 # This class doesn't have a .test member, but # we can add one to the instance anyway. Note # that this will only be a member of classinstance. >>> classinstance.test = 10 >>> classinstance.test 10

Exceptions in Python

Exceptions in Python are handled in try-except blocks:

Def some_function(): try: # Division by zero raises an exception 10 / 0 except ZeroDivisionError: print "Oops, invalid." else: # Exception didn't occur, we're good. pass finally: # This is executed after the code block is run # and all exceptions have been handled, even # if a new exception is raised while handling. print "We"re done with that." >>> some_function() Oops, invalid. We"re done with that.

Importing modules in Python

External libraries are used after import using the import keyword. You can also use from import to import individual functions.

Import random from time import clock randomint = random.randint(1, 100) >>> print randomint 64

Working with files in Python

Python has a large number of libraries for working with files. For example, serialization (converting data to strings with the pickle library):

Import pickle mylist = ["This", "is", 4, 13327] # Open the file C:\\binary.dat for writing. The letter r before the # filename string is used to prevent backslash escaping. myfile = open(r"C:\\binary.dat", "w") pickle.dump(mylist, myfile) myfile.close() myfile = open(r"C:\\text.txt", "w" ) myfile.write("This is a sample string") myfile.close() myfile = open(r"C:\\text.txt") >>> print myfile.read() "This is a sample string" myfile .close() # Open the file for reading. myfile = open(r"C:\\binary.dat") loadedlist = pickle.load(myfile) myfile.close() >>> print loadedlist ["This", "is", 4, 13327]

Miscellaneous

  • Conditions can stick together, for example 1< a < 3 проверит, что a одновременно меньше 3 и больше 1.
  • You can use del to remove variables or elements in arrays.
  • Lists provide very powerful data manipulation capabilities. You can compose an expression using for followed by if or for statements:
>>> lst1 = >>> lst2 = >>> print >>> print # Check if a condition is true for any items. # "any" returns true if any item in the list is true. >>> any(]) True # This is because 4 % 3 = 1, and 1 is true, so any() # returns True. # Check for how many items a condition is true. >>> sum(1 for i in if i == 4) 2 >>> del lst1 >>> print lst1 >>> del lst1
  • Global variables are declared outside of functions and can be read without special declarations inside, but if you want to write them out, you must declare from at the beginning of the function using the special "global" keyword, otherwise Python will assign a new value to the local variable:
number = 5 def myfunc(): # This will print 5. print number def anotherfunc(): # This raises an exception because the variable has not # been bound before printing. Python knows that it an # object will be bound to it later and creates a new, local # object instead of accessing the global one. print number number = 3 def yetanotherfunc(): global number # This will correctly change the global. number = 3

How to learn the Python programming language

This material does not claim to be a comprehensive guide to Python. The Python programming language has a huge number of libraries and various functionality that you will get to know by continuing to work with the language and studying additional sources.

If the above information is not enough for you - check out the extended material describing the Python programming language - - it provides information about the language in more detail.

Among other materials, I recommend Learn Python The Hard Way. And of course The Python 2 Tutorial and The Python 3 Tutorial .

Many thanks to Stavros Korokithakis for his excellent tutorial "Learn Python in 10 minutes".

If you want to improve something in this material - please write in the comments.

Language syntax Python in many ways similar to the syntax of languages ​​such as Perl, C and Java, but at the same time has a number of differences from these programming languages. In this article, we will look at the necessary basics this programming language.

First Python program:

First, it should be noted that on Python you can program in two modes: interactive and scripted

Interactive programming mode:

Without passing a file name as an argument, it will run Python interpreter:

Enter the following text after the prompt line Python and press Enter:

>>> print "Hello, Python!"

If you did everything correctly, then the interpreter will issue the line:

If you get an error, make sure that you have rewritten the code correctly and that you are using the 2.x interpreter (for version 3.x, you should use the command print ("Hello, Python"))

Script programming mode:

Run in python command line with the name of the file (it is also called a script) as a parameter, will start executing the code written in this file. After the script execution is completed, the interpreter will be inactive again.

Let's create a simple script program in Python. Open any text editor (Sublime, Notepad++, gedit...), create a file in it with the name test and extension .py (all files containing code in Python must have an extension .py) and write the code already familiar to us into this file and save the file:

Print "Hello, Python!"

(It is assumed that Python interpreter you have it set in the PATH variable, that is, you can enter python in any directory to launch the interpreter)

After that, enter the following line at the command prompt and press Enter:

Identifiers in Python:

Identifiers in Python are names used to refer to a variable, function, class, module, or other object. The identifier must begin with a letter (a through Z) or an underscore (_), followed by any number of letters, underscores, and numbers (0 through 9).

AT Python punctuation marks or special characters such as @, $ or % are not allowed as identifiers. Besides, Python case sensitive, that is cat and cat they are two different names.

Python has the following convention for naming identifiers:

  • Class names start with a capital letter, all other identifiers start with a small letter.
  • The use of an underscore as the first character of an identifier means that the given identifier is private (secured from use outside the class).
  • If an identifier starts and ends with two underscores (e.g. __init__) it means that it is a special name defined within the language.

Reserved (keyword) words in Python:

This table contains all Python keywords.

and elif if print
as else import raise
assert except in return
break exec is try
class finally lambda while
continue for not which
def from or yield
del global pass

These reserved words cannot be used as a variable name or any other identifier. All Python keywords consist only of lowercase letters. It is possible to get a list of keywords in the interpreter with the command

Help("keywords")

Lines and indents:

One of the first features Python What catches the eye of programmers starting to learn this programming language is that it does not use parentheses to denote individual blocks of code. Instead of them in Python colons and indentation are used.

The number of spaces in the indents is arbitrary and is chosen by everyone at their discretion, however, by agreement it is equal to four spaces. In this case, the indentation of the entire block should be the same.

For example, this block of code will work (although you shouldn't write it like this):

If True: print "Hi" else: print "Bye"

This one will throw an error:

If True: print "Hi" print "Bye"

Thus, in Python multiple lines of code with the same indentation will form a separate block of code. Thanks to such a system, the readability of the code is greatly increased and the habit of writing is clearly and structured.

Multiline expressions:

Expressions in Python usually end with a newline. However, in this programming language there is a special line break character (\), indicating that the code does not end with the end of the line. For example:

Total = item1 + \item2 + \item3

Expressions that are inside square brackets ((), curly brackets (( )) or round brackets (()) do not need a line break character. For example:

Days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]

Quotes in Python:

AT Python You can use single ("), double (""), and triple (""" or """) quotes to denote a string data type, and the string must start and end with the same quotes. A string spanning multiple lines of code must be enclosed in triple quotes. For example:

Name = "wasd" description = "Some text" biography = """ Some long text for few lines of code """

Have questions?

Report a typo

Text to be sent to our editors: