Python basics at a glance. A Brief Overview of the Python Language

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

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

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

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

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

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

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

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

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

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

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

A little theory.

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

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

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

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

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

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

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

Cycles.

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

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

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

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

For variable in list:
teams

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

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

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

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

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

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

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

And a small example with a loop.

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

Input Output

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

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

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

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

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

That's it for the first lesson.

Homework.

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

Introduction


Due to the currently observed rapid development of personal computing technology, there is a gradual change in the requirements for programming languages. Interpreted languages ​​are beginning to play an increasingly important role, as the growing power of personal computers begins to provide sufficient speed for the execution of interpreted programs. And the only significant advantage of compiled programming languages ​​is the high-speed code they produce. When the speed of program execution is not a critical value, the most correct choice would be an interpreted language, as a simpler and more flexible programming tool.

In this regard, it is of some interest to consider the relatively new programming language Python (Python), which was created by its author Guido van Rossum in the early 90s.

General information about Python. Advantages and disadvantages


Python is an interpreted, natively object-oriented programming language. It is extremely simple and contains a small number of keywords, but is also very flexible and expressive. This is a higher-level language than Pascal, C++ and, of course, C, which is achieved mainly through built-in high-level data structures (lists, dictionaries, tuples).

Advantages of language.
An undoubted advantage is that the Python interpreter is implemented on almost all platforms and operating systems. The first such language was C, but its data types on different machines could take up different amounts of memory and this served as some obstacle to writing a truly portable program. Python does not have this disadvantage.

The next important feature is the extensibility of the language; great importance is attached to this and, as the author himself writes, the language was conceived precisely as extensible. This means that it is possible for all interested programmers to improve the language. The interpreter is written in C and the source code is available for any manipulation. If necessary, you can insert it into your program and use it as a built-in shell. Or, by writing your own additions to Python in C and compiling the program, you can get an “extended” interpreter with new capabilities.

The next advantage is the presence of a large number of modules connected to the program, providing various additional capabilities. Such modules are written in C and Python itself and can be developed by all sufficiently qualified programmers. Examples include the following modules:

  • Numerical Python - advanced mathematical capabilities such as manipulation of integer vectors and matrices;
  • Tkinter - building applications using a graphical user interface (GUI) based on the Tk interface widely used on X-Windows;
  • OpenGL - use of an extensive library of graphic modeling of two- and three-dimensional objects Open Graphics Library from Silicon Graphics Inc. This standard is supported, among other things, in such common operating systems as Microsoft Windows 95 OSR 2, 98 and Windows NT 4.0.
Disadvantages of language.
The only drawback noticed by the author is the relatively low execution speed of the Python program, which is due to its interpretability. However, in our opinion, this is more than compensated by the advantages of the language when writing programs that are not very critical to execution speed.

Features Overview


1. Python, unlike many languages ​​(Pascal, C++, Java, etc.), does not require variable declarations. They are created at the place where they are initialized, i.e. the first time a variable is assigned a value. This means that the type of a variable is determined by the type of the assigned value. In this respect, Python resembles Basic.
The type of a variable is not immutable. Any assignment to it is correct and this only leads to the fact that the type of the variable becomes the type of the new assigned value.

2. In languages ​​such as Pascal, C, C++, organizing lists presented some difficulties. To implement them, it was necessary to thoroughly study the principles of working with pointers and dynamic memory. And even with good qualifications, the programmer, each time re-implementing the mechanisms for creating, working and destroying lists, could easily make subtle errors. In view of this, some tools have been created for working with lists. For example, Delphi Pascal has a TList class that implements lists; The STL (Standard Template Library) library has been developed for C++, containing structures such as vectors, lists, sets, dictionaries, stacks and queues. However, such facilities are not available in all languages ​​and their implementations.

One of the distinctive features of Python is the presence of such structures built into the language itself as tuples(tuple) lists(list) and dictionaries(dictionary), which are sometimes called cards(map). Let's take a closer look at them.

  1. Tuple . It is somewhat reminiscent of an array: it consists of elements and has a strictly defined length. Elements can be any values ​​- simple constants or objects. Unlike an array, the elements of a tuple are not necessarily homogeneous. And what distinguishes a tuple from a list is that a tuple cannot be changed, i.e. we cannot assign something new to the i-th tuple element and cannot add new elements. Thus, a tuple can be called a constant list. Syntactically, a tuple is specified by listing all elements separated by commas, all enclosed in parentheses:

  2. (1, 2, 5, 8)
    (3.14, ‘string’, -4)
    All elements are indexed from scratch. To get the i-th element, you must specify the tuple name then the index i in square brackets. Example:
    t = (0, 1, 2, 3, 4)
    print t, t[-1], t[-3]
    Result: 0 4 2
    Thus, a tuple could be called a constant vector if its elements were always homogeneous.
  3. List . A good, private example of a list is the Turbo Pascal language string. The elements of a line are single characters, its length is not fixed, it is possible to delete elements or, on the contrary, insert them anywhere in the line. The elements of the list can be arbitrary objects, not necessarily of the same type. To create a list, just list its elements separated by commas, enclosing them all in square brackets:


  4. ['string', (0,1,8), ]
    Unlike a tuple, lists can be modified as desired. Access to elements is carried out in the same way as in tuples. Example:
    l = ]
    print l, l, l[-2], l[-1]
    Result: 1 s (2.8) 0
  5. Dictionary . It is reminiscent of the record type in Pascal or the structure type in C. However, instead of the “record field” - “value” scheme, “key” - “value” is used here. A dictionary is a collection of key-value pairs. Here the “key” is a constant of any type (but strings are mainly used), it serves to name (index) some corresponding value (which can be changed).

  6. A dictionary is created by listing its elements (key-value pairs separated by a colon), separated by commas, and enclosing them all in curly braces. To gain access to a certain value, after the dictionary name, write the corresponding key in square brackets. Example:
    d = ("a": 1, "b": 3, 5: 3.14, "name": "John")
    d["b"] = d
    print d["a"], d["b"], d, d["name"]
    Result: 1 3.14 3.14 John
    To add a new key-value pair, simply assign the corresponding value to the element with the new key:
    d["new"] = "new value"
    print d
    Result: ("a":1, "b":3, 5:3.14, "name":"John", "new":"new value")

3. Python, unlike Pascal, C, C++, does not support working with pointers, dynamic memory and address arithmetic. In this way it is similar to Java. As you know, pointers are a source of subtle errors and working with them relates more to low-level programming. To provide greater reliability and simplicity, they were not included in Python.

4. One of the features of Python is how one variable is assigned to another, i.e. when on either side of the operator" = " there are variables.

Following Timothy Budd (), we will call pointer semantics the case when the assignment only leads to the assignment of a reference (pointer), i.e. the new variable becomes just another name, denoting the same memory location as the old variable. In this case, changing the value denoted by the new variable will lead to a change in the value of the old one, because they actually mean the same thing.

When an assignment leads to the creation of a new object (here an object - in the sense of a piece of memory for storing a value of some type) and copying the contents of the assigned variable into it, we call this case copy semantics. Thus, if copy semantics applies when copying, then the variables on either side of the "=" sign will mean two independent objects with the same content. And here, a subsequent change in one variable will not affect the other in any way.

Assignment in Python works like this: if assignable the object is an instance of such types as numbers or strings, then copy semantics applies, but if on the right side there is an instance of a class, list, dictionary or tuple, then pointer semantics applies. Example:
a = 2; b = a; b = 3
print "copy semantics: a=", a, "b=", b
a = ; b = a; b = 3
print "pointer semantics: a=", a, "b=", b
Result:
copy semantics: a= 2 b= 3
pointer semantics: a= b=

For those of you who want to know what's going on here, I'll give you a different take on assignment in Python. If in languages ​​such as Basic, Pascal, C/C++ we dealt with “capacity” variables and constants stored in them (numeric, symbolic, string - it doesn’t matter), and the assignment operation meant “entering” the constant into the assigned variable , then in Python we must already work with “name” variables and the objects they name. (Notice some analogies with Prolog?) What is an object in Python? This is everything that can be given a name: numbers, strings, lists, dictionaries, class instances (which in Object Pascal are called objects), the classes themselves (!), functions, modules, etc. So, when assigning a variable to an object, the variable becomes its “name”, and the object can have as many such “names” as desired and they are all independent of each other.

Now, objects are divided into modifiable (mutable) and immutable. Mutable - those that can change their “internal content”, for example, lists, dictionaries, class instances. And unchangeable ones - such as numbers, tuples, strings (yes, strings too; you can assign a new string obtained from an old one to a variable, but you cannot modify the old string itself).

So, if we write a = ; b = a; b = 3, Python interprets it like this:

  • give the object a "list" " Name a ;
  • give this object another name - b ;
  • modify the null element of an object.

  • This is how we get the “pseudo” semantics of pointers.

    One last thing to say about this: although it is not possible to change the structure of the tuple, the mutable components it contains are still available for modification:

    T = (1, 2, , "string") t = 6 # this is not possible del t # also an error t = 0 # allowed, now the third component is a list t = "S" # error: strings are not mutable

    5. The way Python groups operators is very original. In Pascal, this is done using operator brackets begin-end, in C, C++, Java - curly braces (), in Basic, closing endings of language constructs are used (NEXT, WEND, END IF, END SUB).
    In Python, everything is much simpler: selecting a block of statements is carried out by shifting the selected group by one or more spaces or tab characters to the right relative to the head of the structure to which this block will belong. For example:

    if x > 0: print ‘ x > 0 ’ x = x - 8 else: print ‘ x<= 0 ’ x = 0 Thus, a good style of writing programs, which teachers of the languages ​​Pascal, C++, Java, etc. call for, is acquired here from the very beginning, since it simply cannot be done any other way.

    Description of the language. Control structures



    Exception Handling


    try:
    <оператор1>
    [except[<исключение> [, <переменная>] ]:
    <оператор2>]
    [else <оператор3>]
    Performed<оператор1>, if an exception occurs<исключение>, then it is fulfilled<оператор2>. If<исключение>has a value, it is assigned<переменной>.
    Upon successful completion<оператора1>, performed<оператор3>.
    try:
    <оператор1>
    finally:
    <оператор2>
    Performed<оператор1>. If no exceptions occur, then execute<оператор2>. Otherwise executed<оператор2>and an exception is immediately raised.
    raise <исключение> [<значение>] Throws an exception<исключение>with parameter<значение>.

    Exceptions are just strings. Example:

    My_ex = ‘bad index’ try: if bad: raise my_ex, bad except my_ex, value: print ‘Error’, value

    Declaring Functions



    Class Declaration



    Class cMyClass: def __init__(self, val): self.value = val # def printVal(self): print ' value = ', self.value # # end cMyClass obj = cMyClass (3.14) obj.printVal() obj.value = " string now" obj.printVal () !} Result:
    value = 3.14
    value = string now

    Operators for all types of sequences (lists, tuples, strings)


    Operators for lists (list)


    s[i] = x The i-th element s is replaced by x.
    s = t part of the elements s from i to j-1 is replaced by t (t can also be a list).
    dels removes the s part (same as s = ).
    s.append(x) adds element x to the end of s.
    s.count(x) returns the number of elements s equal to x.
    s.index(x) returns the smallest i such that s[i]==x.
    s.insert(i,j) the part of s, starting from the i-th element, is shifted to the right, and s[i] is assigned to x.
    s.remove(x) same as del s[ s.index(x) ] - removes the first element of s equal to x.
    s.reverse() writes a string in reverse order
    s.sort() sorts the list in ascending order.

    Operators for dictionaries


    File objects


    Created by a built-in function open()(see its description below). For example: f = open('mydan.dat','r').
    Methods:

    Other language elements and built-in functions


    = assignment.
    print [ < c1 > [, < c2 >]* [, ] ] displays values< c1 >, < c2 >to standard output. Places a space between arguments. If there is no comma at the end of the list of arguments, it moves to a new line.
    abs(x) returns the absolute value of x.
    apply( f , <аргументы>) calls function (or method) f with< аргументами >.
    chr(i) returns a one-character string with ASCII code i.
    cmp(x,y) returns negative, zero, or positive if, respectively, x<, ==, или >than y.
    divmod (a, b) returns tuple (a/b, a%b), where a/b is a div b (the integer part of the division result), a%b is a mod b (the remainder of the division).
    eval(s)
    returns the object specified in s as a string. S can contain any language structure. S can also be a code object, for example: x = 1 ; incr_x = eval("x+1") .
    float(x) returns a real value equal to the number x.
    hex(x) returns a string containing the hexadecimal representation of x.
    input(<строка>) displays<строку>, reads and returns a value from standard input.
    int(x) returns the integer value of x.
    len(s) returns the length (number of elements) of an object.
    long(x) returns a long integer value x.
    max(s), min(s) return the largest and smallest element of the sequence s (that is, s is a string, list, or tuple).
    oct(x) returns a string containing a representation of the number x.
    open(<имя файла>, <режим>='r' ) returns a file object opened for reading.<режим>= 'w' - opening for writing.
    ord(c) returns the ASCII code of a character (string of length 1) c.
    pow(x, y) returns the value of x to the power of y.
    range (<начало>, <конец>, <шаг>) returns a list of integers greater than or equal to<начало>and less than<конец>, generated with a given<шагом>.
    raw_input( [ <текст> ] ) displays<текст>to standard output and reads a string from standard input.
    round (x, n=0) returns real x rounded to the nth decimal place.
    str(<объект>) returns a string representation<объекта>.
    type(<объект>) returns the type of the object.
    For example: if type(x) == type(‘’): print ‘ this is a string ’
    xrange (<начало>, <конец>, <шаг>) is similar to range, but only simulates a list without creating it. Used in a for loop.

    Special functions for working with lists


    filter (<функция>, <список>) returns a list of those elements<спиcка>, for which<функция>takes the value "true".
    map(<функция>, <список>) applies<функцию>to each element<списка>and returns a list of results.
    reduce ( f , <список>,
    [, <начальное значение> ] )
    returns the value obtained by "reduction"<списка>function f. This means that there is some internal variable p that is initialized<начальным значением>, then, for each element<списка>, the function f is called with two parameters: p and the element<списка>. The result returned by f is assigned to p. After going through everything<списка>reduce returns p.
    Using this function, you can, for example, calculate the sum of the elements of a list: def func (red, el): return red+el sum = reduce (func, , 0) # now sum == 15
    lambda [<список параметров>] : <выражение> An "anonymous" function that does not have a name and is written where it is called. Accepts the parameters specified in<списке параметров>, and returns the value<выражения>. Used for filter, reduce, map. For example: >>>print filter (lambda x: x>3, ) >>>print map (lambda x: x*2, ) >>>p=reduce (lambda r, x: r*x, , 1) >>> print p 24

    Importing Modules



    Standard math module


    Variables: pi, e.
    Functions(similar to C language functions):

    acos(x) cosh(x) ldexp(x,y) sqrt(x)
    asin(x) exp(x) log(x) tan(x)
    atan(x) fabs(x) sinh(x) frexp(x)
    atan2(x,y) floor(x) pow(x,y) modf(x)
    ceil(x) fmod(x,y) sin(x)
    cos(x) log10(x) tanh(x)

    string module


    Functions:

    Conclusion


    Due to the simplicity and flexibility of the Python language, it can be recommended to users (mathematicians, physicists, economists, etc.) who are not programmers, but who use computer technology and programming in their work.
    Programs in Python are developed on average one and a half to two (and sometimes two to three) times faster than in compiled languages ​​(C, C++, Pascal). Therefore, the language may be of great interest to professional programmers who develop applications that are not critical to execution speed, as well as programs that use complex data structures. In particular, Python has proven itself well in developing programs for working with graphs and generating trees.

    Literature


    1. Budd T. Object-oriented programming. - St. Petersburg: Peter, 1997.
    2. Guido van Rossum. Python Tutorial. (www.python.org)
    3. Chris Hoffman. A Python Quick Reference. (www.python.org)
    4. Guido van Rossum. Python Library Reference. (www.python.org)
    5. Guido van Rossum. Python Reference Manual. (www.python.org)
    6. Guido van Rossum. Python programming workshop. (http://sultan.da.ru)
    August 27, 2012 at 03:18 pm

    Learn Python efficiently

    • Python

    Hello everyone!

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

    Why do I need your Python?

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

    Where is Python used?

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

    Literature

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

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

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

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

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

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

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

    I want practice!

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

    In which, in a condensed form,
    talk about the basics of the Python language. I offer you a translation of this article. The translation is not literal. I tried to explain in more detail some points that may not be clear.

    If you are planning to learn the Python language, but cannot find a suitable guide, then this
    The article will be very useful to you! In a short time, you can get to know
    basics of the Python language. Although this article often relies
    that you already have programming experience, but, I hope, even for beginners
    this material will be useful. Read each paragraph carefully. Due to
    the conciseness of the material, some topics are discussed superficially, but contain all
    required metric.

    Basic properties

    Python does not require explicit declaration of variables, and is a case-sensitive (var variable is not equivalent to Var or VAR - they are three different variables) object-oriented language.

    Syntax

    Firstly, it is worth noting an interesting feature of Python. It does not contain operator brackets (begin..end in pascal or (..) in C), instead blocks are indented: spaces or tabs, and entering a block of statements is done with a colon. Single-line comments begin with a pound sign "#", multi-line comments begin and end with three double quotes """".
    To assign a value to a variable, use the “=” sign, and to compare -
    "==". To increase the value of a variable, or add to a string, use the “+=” operator, and “-=” to decrease it. All of these operations can interact with most types, including strings. For example


    >>> myvar = 3
    >>> myvar += 2
    >>> myvar -= 1
    ""This is a multi-line comment
    Lines enclosed in three double quotes are ignored"""

    >>> mystring = "Hello"
    >>> mystring += "world."
    >>> print mystring
    Hello world.
    # The next line changes
    the values ​​of the variables are swapped. (Just one line!)

    >>> myvar, mystring = mystring, myvar

    Data structures

    Python contains data structures such as lists, tuples and dictionaries). Lists are similar to one-dimensional arrays (but you can use a List including lists - a multidimensional array), tuples are immutable lists, dictionaries are also lists, but indexes can be of any type, not just numeric. "Arrays" in Python can contain data of any type, that is, one array can contain numeric, string, and other data types. Arrays start at index 0 and the last element can be accessed at index -1 You can assign functions to variables and use them accordingly.


    >>> sample = , ("a" , "tuple" )] #The list consists of an integer, another list and a tuple
    >>> #This list contains a string, an integer and a fraction
    >>> mylist = “List item 1 again” #Change the first (zero) element of the sheet mylist
    >>> mylist[-1 ] = 3 .14 #Change the last element of the sheet
    >>> mydict = ("Key 1" : "Value 1" , 2 : 3 , "pi" : 3 .14 ) #Create a dictionary with numeric and integer indexes
    >>> mydict["pi" ] = 3 .15 #Change the dictionary element under the index “pi”.
    >>> mytuple = (1 , 2 , 3 ) #Specify a tuple
    >>> myfunction = len #Python allows you to declare function synonyms this way
    >>> print myfunction(list)
    3

    You can use part of an array by specifying the first and last index separated by a colon ":". In this case, you will receive part of the array, from the first index to the second, not inclusive. If the first element is not specified, then the count starts from the beginning of the array, and if the last element is not specified, then the array is read to the last element. Negative values ​​determine the position of the element from the end. For example:


    >>> mylist = [“List item 1” , 2 , 3 .14 ]
    >>> print mylist[:] #All elements of the array are read
    ["List item 1" , 2 , 3 .14000000000000001 ]
    >>> print mylist #The zero and first element of the array are read.
    ["List item 1" , 2 ]
    >>> print mylist[-3 :-1 ] #Elements are read from zero (-3) to second (-1) (not inclusive)
    ["List item 1" , 2 ]
    >>> print mylist #Elements are read from first to last

    Strings

    Strings in Python separated by double quotes """ or single quotes """. Double quotes can contain single quotes, or vice versa. For example, the line “He said hello!” will be displayed as "He said hi!". If you need to use a string of several lines, then this line must begin and end with three double quotes """". You can substitute elements from a tuple or dictionary into the string template. The percent sign "%" between the string and the tuple replaces characters in the string “%s” to a tuple element. Dictionaries allow you to insert an element at a given index into a string. To do this, use the “%(index)s” construction in the string. In this case, instead of “%(index)s” the dictionary value at the given index will be substituted. index.


    >>>print "Name: %s\nNumber: %s\nString: %s"% (my class.name, 3 , 3 * "-" )
    Name: Poromenos
    Number: 3
    String: -
    strString = """This text is located
    on several lines"""

    >>> print“This %(verb)s a %(noun)s.” %("noun" : "test" , "verb" : "is")
    This is a test.

    Operators

    While statements if, for make up move operators. There is no equivalent to the select statement, so you'll have to make do if. In the operator for comparison takes place variable and list. To get a list of digits up to a number - use the range( function ). Here is an example of using operators


    rangelist = range(10) #Get a list of ten numbers (from 0 to 9)
    >>> print rangelist
    for number in rangelist: #As long as the number variable (which increases by one each time) is included in the list...
    # Check if the variable is included
    # numbers to a tuple of numbers(3 , 4 , 7 , 9 )
    if number in (3 , 4 , 7 , 9 ): #If the variable number is in the tuple (3, 4, 7, 9)...
    # Operation " break» provides
    # exit the loop at any time
    break
    else :
    # « continue"scrolls"
    # loop. This is not required here, since after this operation
    # in any case, the program goes back to processing the loop
    continue
    else :
    # « else» It is not necessary to indicate. The condition is met
    # if the loop was not interrupted with " break».
    pass # Nothing to do

    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

    To declare a function, use keyword " def» . Function arguments are given in parentheses after the function name. You can specify optional arguments, giving them a default value. Functions can return tuples, in which case you need to write the return values ​​separated by commas. Keyword " lambda" is used to declare elementary functions.


    # arg2 and arg3 are optional arguments, take the value declared by default,
    # unless you give them a different value when calling the function.
    def myfunction(arg1, arg2 = 100 , arg3 = "test" ):
    return arg3, arg2, arg1
    #The function is called with the value of the first argument - "Argument 1", the second - by default, and the third - "Named argument".
    >>>ret1, ret2, ret3 = myfunction("Argument 1" , arg3 = "Named argument")
    # ret1, ret2 and ret3 take the values ​​"Named argument", 100, "Argument 1" respectively
    >>> print ret1, ret2, ret3
    Named argument 100 Argument 1

    # The following entry is equivalent def f(x): return x+1
    functionvar = lambda x:x+1
    >>> print functionvar(1)
    2

    Classes

    The Python language is limited in multiple inheritance in classes. Internal variables and internal class methods begin with two underscores "__" (for example "__myprivatevar"). We can also assign a value to a class variable from outside. Example:


    class My class:
    common = 10
    def __init__(self):
    self .myvariable = 3
    def myfunction(self , arg1, arg2):
    return self .myvariable

    # Here we have declared the class My class. The __init__ function is called automatically when classes are initialized.
    >>> classinstance = My class() # We have initialized the class and the myvariable variable has the value 3 as stated in the initialization method
    >>> #Method myfunction of class My class returns the value of the variable myvariable
    3
    # The common variable is declared in all classes
    >>> classinstance2 = My class()
    >>> classesinstance.common
    10
    >>> classesinstance2.common
    10
    # So if we change its value in the My class class will change
    # and its values ​​in objects initialized by the My class class
    >>> Myclass.common = 30
    >>> classesinstance.common
    30
    >>> classesinstance2.common
    30
    # And here we do not change the class variable. Instead of this
    # we declare it in an object and assign it a new value
    >>> classesinstance.common = 10
    >>> classesinstance.common
    10
    >>> classesinstance2.common
    30
    >>> Myclass.common = 50
    # Now changing the class variable will not affect
    # variable objects of this class
    >>> classesinstance.common
    10
    >>> classesinstance2.common
    50

    # The next class is a descendant of the My class class
    # by inheriting its properties and methods, who can the class
    # inherit from several classes, in this case the entry
    # like this: class Otherclass(Myclass1, Myclass2, MyclassN)
    class Otherclass(Myclass):
    def __init__(self, arg1):
    self .myvariable = 3
    print arg1

    >>> classinstance = Otherclass("hello")
    hello
    >>> classesinstance.myfunction(1 , 2 )
    3
    # This class does not have the property test, but we can
    # declare such a variable for an object. Moreover
    # this variable will only be a member class instance.
    >>> classinstance.test = 10
    >>> classesinstance.test
    10

    Exceptions

    Exceptions in Python have a structure try-except [except ionname]:


    def somefunction():
    try :
    # Division by zero causes an error
    10 / 0
    except ZeroDivisionError:
    # But the program does not "Perform an illegal operation"
    # And handles the exception block corresponding to the “ZeroDivisionError” error
    print"Oops, invalid."

    >>>fn except()
    Oops, invalid.

    Import

    External libraries can be connected using the procedure “ import", where is the name of the library being connected. You can also use the command " from import" so you can use a function from the library


    import random #Import the “random” library
    from time import clock #And at the same time the “clock” function from the “time” library

    Randomint = random .randint(1 , 100 )
    >>> print randomint
    64

    Working with the file system

    Python has many built-in libraries. In this example, we will try to save a list structure in a binary file, read it and save the string in a text file. To transform the data structure we will use the standard library "pickle"


    import pickle
    mylist = ["This" , "is" , 4 , 13327 ]
    # Open the file C:\binary.dat for writing. "r" symbol
    # prevents replacement of special characters (such as \n, \t, \b, etc.).
    myfile = file (r"C:\binary.dat" , "w")
    pickle .dump(mylist, myfile)
    myfile.close()

    Myfile = file (r"C:\text.txt" , "w")
    myfile.write("This is a sample string" )
    myfile.close()

    Myfile = file (r"C:\text.txt")
    >>> print myfile.read()
    "This is a sample string"
    myfile.close()

    # Open the file for reading
    myfile = file (r"C:\binary.dat")
    loadedlist = pickle .load(myfile)
    myfile.close()
    >>> print loadedlist
    ["This" , "is" , 4 , 13327 ]

    Peculiarities

    • Conditions can be combined. 1 < a < 3 выполняется тогда, когда а больше 1, но меньше 3.
    • Use the operation " del" to clear variables or array elements.
    • Python offers great opportunities for working with lists. You can use list structure declaration operators. Operator for allows you to specify list elements in a specific sequence, and if- allows you to select elements by condition.
    >>> lst1 =
    >>> lst2 =
    >>> print
    >>> print
    # The "any" operator returns true if although
    # if one of the conditions included in it is satisfied.
    >>> any(i % 3 for i in )
    True
    # The following procedure counts the number
    # matching elements in the list
    >>> sum (1 for i in if i == 3)
    3
    >>> del lst1
    >>> print lst1
    >>> del lst1
    • Global Variables are declared outside functions and can be read without any declarations. But if you need to change the value of a global variable from a function, then you need to declare it at the beginning of the function with the keyword " global" if you don't do this, then Python will declare a variable that is only accessible to that function.
    number = 5

    def myfunc():
    # Outputs 5
    print number

    def anotherfunc():
    # This throws an exception because the global variable
    # was not called from a function. Python in this case creates
    # variable of the same name inside this function and accessible
    # only for operators of this function.
    print number
    number = 3

    def yetanotherfunc():
    global number
    # And only from this function the value of the variable is changed.
    number = 3

    Epilogue

    Of course, this article does not describe all the features of Python. I hope this article will help you if you want to continue learning this programming language.

    Benefits of Python

    • The execution speed of programs written in Python is very high. This is due to the fact that the main Python libraries
      are written in C++ and take less time to complete tasks than other high-level languages.
    • Because of this, you can write your own Python modules in C or C++
    • In the standard Python libraries you can find tools for working with email, protocols
      Internet, FTP, HTTP, databases, etc.
    • Scripts written using Python run on most modern operating systems. This portability allows Python to be used in a wide variety of areas.
    • Python is suitable for any programming solutions, be it office programs, web applications, GUI applications, etc.
    • Thousands of enthusiasts from all over the world worked on the development of Python. The support for modern technologies in standard libraries can be attributed to the fact that Python was open to everyone.

    Tags:

    • Python
    • programming
    • lesson
    Add tags

    Python is a widely used, high-level programming language that was named after the famous British comedy television show " Monty Python's Flying Circus" The Python language is simple in structure, yet incredibly flexible and powerful. Given that Python code is easy to read and without being too rigid in syntax, many consider it to be the best introductory programming language.

    Python - description of the language given in Foundation describes Python:

    Python is an interpreted, interactive, object-oriented programming language. It includes modules, exceptions, dynamic typing, high-level dynamic data types, and classes. Python combines excellent performance with clear syntax. It provides interfaces to many system calls and libraries, as well as various window systems, and is extensible with C and C++. Python is used as an extension language for applications that require a programming interface. Finally, Python is a cross-platform language: it runs on many versions of Unix, Macs, and computers running MS-DOS, Windows, Windows NT, and OS/2.

    Which programming language should you learn first?

    You can start learning the Python programming language. To illustrate how Python differs from other introductory languages, think back to when you were a teenager.

    Learning to program with Python is like driving your parents' minivan. Once you've driven it around a few times in a parking lot, you'll begin to understand how to handle the car.

    Trying to learn programming using C ( or even assembler) it's like learning to drive by assembling your parents' minivan. You'll be stuck in a garage for years putting parts together, and by the time you have a full understanding of how the car works and are able to troubleshoot and predict future problems, you'll be burned out before you ever get behind the wheel.

    Benefits of Python

    Python is a universal language for beginners. You can automate workflows, create websites, and create desktop applications and games using Python. By the way, the demand for Python developers ( PostgreSQL, OOP, Flask, Django) has grown dramatically over the past few years in companies such as Instagram, Reddit, Tumblr, YouTube and Pinterest.

    High-level general purpose language

    Python is a high-level programming language. Using it, you can create almost any type of software. This versatility keeps you interested as you develop programs and solutions that target your interests rather than getting stuck in the weeds of a language worrying about its syntax.

    Interpreted language

    The Python programming language for beginners is interpreted, which means you don't need to know how to compile code. Since there is no compilation step, productivity increases and time for editing, testing and debugging is greatly reduced. Just download the IDE ( IDE), write your code and click “Run” ( Run).

    Code readability is key

    Python's simple, easy-to-learn syntax emphasizes readability and sets a good programming style. With Python, you can express your concept in fewer lines of code. This language also forces you to think about program logic and algorithms. Because of this, it is often used as a scripting or integration language ( glue language) to link existing components together and write large volumes of easily readable and runnable code in short periods of time.

    It's just fun

    You can't name a programming language after Monty Python without having a sense of humor. Moreover, testing was carried out to compare the time required to write a simple script in different languages ​​( Python, Java, C, J, BASIC):

    ...Python requires less time, fewer lines of code, and fewer concepts to achieve your goal... And to top it all off, Python programming is fun! Having fun and frequent success builds confidence and interest in students, who become better prepared to continue learning Python.

    Translation of the article “Why Learn Python? "was prepared by the friendly project team.

    Good bad