• Python language. What You Can Do with Python

    Python Programming

    Part 1. Language capabilities and basic syntax

    Content Series:

    Is it worth learning Python?

    Python is one of the most popular modern languages programming. It is suitable for solving a variety of problems and offers the same capabilities as other programming languages: dynamism, OOP support and cross-platform. The development of Python began by Guido Van Rossum back in the mid-1990s, so by now it has been possible to get rid of standard “childhood” diseases, significantly develop the best aspects of the language and attract many programmers using Python to implement their projects.

    Many programmers believe that it is necessary to learn only “classic” programming languages ​​such as Java or C++, since other languages ​​will not be able to provide the same capabilities anyway. However, in lately a belief arose that it is advisable for a programmer to know more than one language, as this broadens his horizons, allowing him to more creatively solve problems and increasing his competitiveness in the labor market.

    Learning two languages ​​like Java and C++ perfectly is quite difficult and would take a lot of time; in addition, many aspects of these languages ​​contradict each other. At the same time, Python is ideal for the role of a second language, since it is immediately absorbed thanks to the already existing knowledge of OOP, and the fact that its capabilities do not conflict, but complement the experience gained from 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. Thanks to its brevity, it will allow you to quickly master the syntax of the language, and the absence of “legacy” in the form of axioms formed over many years will help you quickly master OOP. Due to these factors, the learning curve for Python will be quite short, and the programmer will be able to move from educational examples to commercial projects.

    Therefore, no matter who the reader of this article is - an experienced programmer or a beginner in the field of software development, the answer to the question, which 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, starting with the most basic principles language to its advanced capabilities in terms of integration with other technologies. The first article will cover the basic features and syntax of Python. In the following, we'll look at more advanced 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 exactly the same way, providing the syntax for forming expressions that form executable programs, and a dictionary – a set of functionality in the form of a standard library and plug-ins.

    As mentioned, Python's syntax is quite concise, especially when compared to Java or C++. On the one hand, this is good, since the simpler the syntax, the easier it is to learn and the fewer mistakes you can make while using it. However, such languages ​​have a drawback - they can be used to convey the most simple information and complex constructs cannot be expressed.

    This does not apply to Python, since it is a simple but simplified language. The fact is that Python is a language with more high level abstraction, higher, for example, than Java and C++, and allows you to convey the same amount of information in a smaller amount of source code.

    Also Python is a language general purpose, therefore can be used in almost any area of ​​software development (standalone, client-server, Web applications) and in any subject area. In addition, Python integrates easily with existing components, allowing you to embed Python into already written applications.

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

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

    The Java runtime environment also 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 into machine code on the target platform.

    On at the moment There are three well-known runtime implementations for Python: CPython, Jython, and Python.NET. As you can guess from the name, the first environment is implemented in C, the second in Java language, and the latter is on the .NET platform.

    The CPython runtime is usually called simply Python, and when people talk about Python, they most often mean this implementation. 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, pre-compiled versions of the runtime exist for various operating systems, including different versions OS Windows and various Linux distributions. In this and subsequent articles, CPython will be considered, unless otherwise stated separately.

    The Jython runtime is a Python implementation for working with Java virtual machine(JVM). Any JVM version is supported, starting from version 1.2.2 (the current Java version is 1.6). Working with Jython requires an installed Java machine (Java runtime environment) and some knowledge of the Java programming language. It is not necessary to know how to write source code in Java, but you will have to deal 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 the 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 runtime environments are released under a license compatible with the well-known GPL license, so they can be used for the development of both commercial and free software. Most Python extensions are also GPL-licensed and can be freely used in any project, but there are also commercial extensions or extensions with more stringent licenses. Therefore, when using Python in a commercial project, you need to know what restrictions exist in the extension plug-in licenses.

    Getting started with Python

    Before you start using Python, you need to install its execution environment - in this article this is CPython and, accordingly, the python interpreter. There are various ways installation: advanced users can compile Python themselves from its publicly available source code, or you can download ready-made ones from the website www.python.org executable files for a specific operating system, and finally, many Linux distributions come with a Python interpreter already pre-installed. This article uses the Windows version of Python 2.x, but the examples presented 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 it can be found by operating system.
    • 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 (list elements must be separated by a system delimiter).
    • PYTHONSTARTUP. An optional variable that specifies the path to the 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 start in interactive mode. This mode launches a special Python shell into which you can enter individual commands or expressions, and their value will be immediately calculated. It is very convenient during learning Python, since you can immediately check the correctness of a particular design.

    The value of the evaluated expression is stored in a special variable called Single Underscore (_) so that it can be used in subsequent expressions. You can end an interactive session using the keyboard shortcut 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 specific command to be executed by the interpreter, or the path to a file that contains the script to be executed. 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 subsequent processing to the executable script; they are passed to the program as strings and separated by spaces.

    To verify that Python is installed correctly and is working properly, you can run the following commands:

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

    The -v option prints 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, since they are ordinary text files, but there are also 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 lines. The # symbol is used to denote comments. The interpreter ignores comments and empty lines.

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

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

    Data Types Used in Python

    The data types used in Python are also the same as other languages ​​- integer and real data types; Additionally, complex data type is supported - with real and imaginary parts (an example of such a number is 1.5J or 2j, where J represents square root from -1). Python supports strings that can be enclosed in single, double, or triple quotes, and strings, like Java, are immutable objects, i.e. cannot change their value after creation.

    Python also has a logical data type bool with two value options – True and False. However, in older versions of Python there was no such data type, and furthermore, any data type could be cast to boolean value True or False. All non-zero numbers and non-empty strings or collections of data were treated as True, and empty and zero values ​​were treated as False. This feature has been preserved in new versions of Python, however, to increase code readability, it is recommended to use the bool type for boolean variables. At the same time, if you need to maintain backward compatibility with older Python implementations, then you should use 1 (True) or 0 (False) as boolean variables.

    Functionality for working with data sets

    Python defines three types of collections for storing data sets:

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

    A tuple is an immutable ordered sequence of data. It may contain elements various types, for example other tuples. A tuple is defined in parentheses and its elements are separated by commas. A 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. List elements are also separated by commas, but are specified in square brackets. To create lists, the list() function is proposed.

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

    Listing 1. Types of collections 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' ) # dictionary of three elements with keys of type int

    Defining Functions in Python

    Although Python supports OOP, many of its features are implemented as separate functions; In addition, extension modules are most often made 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; taking into account the above requirements:

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

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

    FUNCTION_NAME(parameters)

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

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

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

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

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

    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 it's all 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 program 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, starting from searching for text using a template and ending with 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 simple 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 keyboard input, 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, language JavaScript programming 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. You shouldn’t be surprised by this, 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! For 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 interesting feature 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 containing 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 obtained at index -1 You can assign function 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 # 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

    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
    # 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 in binary file list structure, read it and store the line in 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 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 standard Python libraries you can find tools to work with by 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 range of applications.
    • Python is suitable for any programming solution, 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

    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 one. "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 a built-in scripting language in many games, and not only (in office suite OpenOffice.org, 3D editor Blender, 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 far from full list 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 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? Very simple, on help will come range function

    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 cycle.

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

    I/O

    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 view. 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.

    (Translation)

    An article was published on the Poromenos Stuff website in which, in a concise form, they 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 article will be very useful to you! In a short time, you will be able to get acquainted with the basics of the Python language. Although this article often relies on you already having programming experience, I hope even beginners will find this material useful. Read each paragraph carefully. Due to the condensation of the material, some topics are discussed superficially, but contain all the necessary material.

    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, the “=” sign is used, and for comparison, “==” is used. 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

    Strings 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 containing 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

    >>> mylist = ["List item 1", 2, 3.14] #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 indices

    >>> mydict["pi"] = 3.15 #Change the dictionary element under index "pi".

    >>> mytuple = (1, 2, 3) #Specify a tuple

    >>> myfunction = len #Python allows you to declare function synonyms this way

    >>> print myfunction(mylist)

    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 array elements are read

    ["List item 1", 2, 3.1400000000000001]

    >>> print mylist #The zeroth and first elements of the array are read.

    ["List item 1", 2]

    >>> print mylist[-3:-1] #Elements from zero (-3) to second (-1) are read (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" % (myclass.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

    The while, if, and for statements constitute move operators. There's no equivalent to a select statement, so you'll have to make do with if . The for statement makes a comparison 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 digits (from 0 to 9)

    >>> print rangelist

    for number in rangelist: #As long as the variable number (which is incremented by one each time) is 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 number is in the tuple (3, 4, 7, 9)...

    # The "break" operation provides

    # exit the loop at any time

    Break

    Else:

    # "continue" performs "scrolling"

    # loop. This is not required here, since after this operation

    # in any case, the program goes back to processing the loop

    Continue

    else:

    # "else" is optional. The condition is met

    # if the loop was not interrupted with "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

    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. The 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 is equivalent to def f(x): return x + 1

    functionvar = lambda x: x + 1

    >>> print functionvar(1)

    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 Myclass:

    Common = 10

    def __init__(self):

    Self.myvariable = 3

    Def myfunction(self, arg1, arg2):

    Return self.myvariable

    # Here we have declared the class Myclass. The __init__ function is called automatically when classes are initialized.

    >>> classinstance = Myclass() # We have initialized the class and myvariable has the value 3 as stated in the initialization method

    >>> classinstance.myfunction(1, 2) #The myfunction method of the Myclass class returns the value of the variable myvariable

    # The common variable is declared in all classes

    >>> classesinstance2 = Myclass()

    >>> classesinstance.common

    >>> classesinstance2.common

    # So if we change its value in the Myclass class it will change

    # and its values ​​in objects initialized by the Myclass class

    >>> Myclass.common = 30

    >>> classesinstance.common

    >>> classesinstance2.common

    # And here we do not change the class variable. Instead

    # we declare it in an object and assign it a new value

    >>> classesinstance.common = 10

    >>> classesinstance.common

    >>> classesinstance2.common

    >>> Myclass.common = 50

    # Now changing the class variable will not affect

    # variable objects of this class

    >>> classesinstance.common

    >>> classesinstance2.common

    # The following class is a descendant of the Myclass 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)

    # This class does not have the property test, but we can

    # declare such a variable for an object. Moreover

    # this variable will be a member of classinstance only.

    >>> classinstance.test = 10

    >>> classesinstance.test

    Exceptions

    Exceptions in Python have a try -except structure:

    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."

    >>> fnexcept()

    Oops, invalid.

    Import

    External libraries can be connected using the “import” procedure, where is the name of the library being connected. You can also use the "from import" command so that 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

    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 "del" operator to clear variables or array elements.
    • Python offers great opportunities for working with lists. You can use list structure declaration operators. The for operator allows you to specify list elements in a certain sequence, and the if operator allows you to select elements based on a 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)

    >>> 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 do not do this, then Python will declare a variable that is accessible only 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 range of applications.
    • 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.