Python Programming Basics. Python Basics at a Glance

ABOUT Python(better pronounced "python", although some say "python") - the subject of this study, is best said by the creator of this programming language, the Dutchman Guido van Rossum:

"Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Built-in high-level data structures combined with dynamic typing and binding make the language attractive for rapid application development (RAD, Rapid Application Development). It can also be used as a scripting language to communicate software components. Python syntax is easy to learn and emphasizes code readability, which reduces software maintenance costs. Python supports modules and packages, encouraging modularity and code reuse. The Python interpreter and large standard library are available freely as source and executable code for all major platforms and can be freely redistributed."

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

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

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

How to describe the language?

This lecture does not aim to describe Python systematically; there is an original reference guide for that. Here it is proposed to consider the language from several aspects simultaneously, which is achieved by a set of examples that will allow you to quickly get acquainted with real programming than in the case of a strict academic approach.

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

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

History of the Python language

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

Do you want to enter the world of programming and quickly write your first few programs? Or do you dream of learning new languages, but don't know where to start? Pay attention to courses on the basics of programming in Python. Next, you will learn more about why this language is recommended for beginners and what programs can be created in it.

Python Basics for Beginner Programmers

Python is a powerful, high-level, object-oriented programming language created by Guido van Rossum. It has an easy-to-use syntax, making it an ideal language for those trying to learn programming for the first time. To continue getting acquainted with the language, you can read the book by Dmitry Zlatopolsky “Python - Basics of Programming”. But we'll start with the very basics. There is a lot of literature in this area. Another option is Harry Percival’s books “Python. Test-driven development.” It talks about language from a practical point of view.

Using the language in practice

So, what is written in Python or “Python”, as it is also called among programmers, and why learn it? Python is a general purpose language. It is used to write web applications using various frameworks, system utilities and applications for automating various actions. There are now enough courses on the basics of programming in Python to try learning the language on your own.

It could become the basis of a new profession, as it has a wide range of applications from web development, scientific and mathematical computing to desktop graphical user interfaces. It is also good for prototyping. That is, a prototype is first created in Python, then the concept can be transferred to faster and compiled programming languages. Using this language, you can create desktop applications with a graphical interface and write games, for which there is a special library. The basics of algorithmization and programming in Python are suitable for creating applications for mobile devices.

Why learn Python

Python also uses a very simple and concise syntax and dynamic typing. Knowledge of the basics of algorithmization and programming in Python allows you to quickly create a program and run it. If you need a language to quickly create applications and scripts across multiple domains, you'll be hard-pressed to find a better alternative than Python. It has a number of obvious advantages over other programming languages:

  • universal use - different types of applications can be written in this language, therefore, along with its mastery, wide opportunities for using this language open up;
  • simplicity - the language was initially developed to simplify human work with it;
  • popularity among programmers and demand in the labor market - Python is widely used in various projects;
  • a large number of available libraries expand the capabilities of the language and make it even more universal;
  • cross-platform - a program written once will work on any platform that has a language interpreter;
  • One of the important advantages of the language is its high-quality documentation.

Python is also one of the oldest web development languages, created by Guido van Rossum at the National Research Institute for Mathematics and Computer Science in the Netherlands in the early 90s. The language borrows heavily from C++, C and other scripting languages. It uses English keywords that make up most of Python programming. If you master them, then you can consider that for the most part you have already mastered the language. This will take some time and you will need to understand the basic concepts before starting. So let's start by getting to know them.

Benefits of Python

One of the key benefits of Python programming is its interpretive nature. This means that the program code is not compiled into an executable file, but is executed by the interpreter every time it is launched by the user. Therefore, to run the program, it must be present on the computer where you will create programs. The interpreter and standard library are available in binary or source form from the Python website and can run smoothly on all major operating systems.

So, the main advantages of Python include:

  • Interpretive: The language is processed by an interpreter at runtime, such as PHP or PERL, so you don't have to compile the program before executing it.
  • Interactivity: You can directly interact with the interpreter while writing your program.
  • Ideal for beginners: for beginner programmers.
  • Python is a great choice because it supports application development, from games to browsers to word processing.

    How to install and run the interpreter

    In order to start writing in Python, you need to download and install its interpreter on the official website of the language, selecting the version for your operating system. It is worth noting that there are two branches of the language - the second and third. It's better to start learning the basics of Python 3 if you haven't installed another version yet. When installing on Windows, be sure to pay attention to whether the Add Python to Path option and the Pip utility are enabled. After installation, you can run it. To do this, you need to enter: “python” in the command line, and it will start. Three angle brackets will appear in the window, indicating that you are in the interpreter. This programming language is also freely available, and you can find tips, third-party tools, programs, modules, and additional documentation.

    Keywords in Python

    In the interpreter, you can perform actions in the language interactively. Each action is performed immediately after pressing Enter. You can use it as an advanced calculator. But writing a large program in an interpreter is too labor-intensive. Therefore, it makes sense to use text editors. The finished text file can then be executed by the interpreter. One of the fundamentals of Python is that any blocks in it are defined by indentation, so you must indent in order to run a block and delete it. The interpreter can be easily extended with new data types or functions in C++ or C. The Python programming language works as an extension for custom applications. What makes this language so easy to learn is the fact that it uses English keywords rather than punctuation, and has fewer syntactic constructs than other programming languages.

    Getting started with Python

    Before you start working outside the interpreter, to create a program, you need to open a text editor and create an empty file with utf-8 encoding and set the extension to “py”. It is best to use special code editors for programmers for this purpose. The first line needs to indicate the encoding. Lines starting with a # are considered comments and are not executed. Python is implicitly and dynamically typed, so you don't need to declare variables. Types are enforced and variables are also case sensitive, so var and VAR are treated as two separate variables. If you want to know how any object works, you just need to type the following: “help(object)”. You can also use the “dir(object)” command to find out all the methods of a particular option, and you can use the “__doc__” object to find out its docstring.

    How to run a written program

    You must also run the written program on the command line. To do this, you need to write the name of the interpreter and, separated by a space, the name of the file with the written program. When starting the program, you must specify the full path to the file. This is not always easy, as the path can be very long, so sometimes it is easier to change the current directory on the command line and start the interpreter there. To do this, you need to go to the desired directory, hold down the shift key, right-click on the directory and select the “open command window” option in the menu that opens. Then the command line will be launched in this directory. Next, in the console window, you need to enter the name of the interpreter and, separated by a space, the name of the file that is located in it.

    Language syntax

    The basics of programming in Python are not too different from other languages, but variables have a slightly different meaning. Python does not have required symbols to complete statements. Any blocks are defined using indentation, so you must indent to start a block and remove it. For multiline comments, you must use multiline strings. Values ​​are assigned using the “=” sign, and equality testing is done with two of them “==”. You can decrease or increase values ​​using the = or -= operators with a sum on the right side. This can work with strings and other data types. You can also use multiple variables on one line.

    Data Types in Python

    Now let's look at data types. Python is based on data structures - dictionaries (dict), tuples (tuples) and lists (lists). Sets can be found in the library of sets, which are available in all versions of Python. Lists are similar to one-dimensional arrays, although you can also have lists of other lists. Dictionaries are essentially associative arrays or hash tables. Tuples are one-dimensional arrays. Now arrays in Python can be of any type, and ypes is always zero. Negative numbers start from the end to the beginning, and -1 is the last element. Variables can also point to functions.

    Strings in Python

    Python strings can use single or double quotes, and you can use one kind of quotation marks in a string using another kind. Multiline strings are enclosed in single or triple double quotes. To fill strings with values, you can use the modulo(%) operator followed by tuple. Each % is replaced by an element of the tuple from left to right, and you can also use dictionary substitutions. Python flow control statements: “while”, “for” and “if”. To branch you need to use “if”. To enumerate through a list, use “for”. To get a list of numbers, use a range.

    Functions in Python

    The keyword “def” is used to declare functions. Binding another object to a variable removes the old one and replaces the immutable types. Optional arguments can be specified in a function declaration after the required arguments, giving them default values. In the case of named arguments, the argument name is assigned a value. Functions can return a tuple, and you can efficiently return multiple values ​​using tuple unboxing. Parameters are passed by reference, but tuples, ints, strings, and other immutable types are immutable because only the memory location of the element is passed.

    You have just begun your acquaintance with the language, so do not be afraid of mistakes and turn to available resources to continue learning this interesting and useful programming language.

    (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 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

    >>> 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 of this

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

    >>> classinstance.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 specific 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.

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

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

    There are many uses for Python, but there are a few that it is particularly good at. Let's figure out what can be done in this language.

    Main differences:

    • Flask provides simplicity, flexibility, and complete control over your project. It allows the user to independently decide how to implement certain things.
    • Django is an all-inclusive service. Out of the box it already has an admin panel, database interfaces, ORM (Object Relational Mapping) and a directory structure for your projects.

    What to choose?

    • Choose Flask if you want more experience and learning opportunities. Or if you need maximum control over all the components used, for example, databases.
    • Choose Django if you're interested in the end product. Especially if you work with simple applications, such as a news site, a store, a blog, and you want every task to be solved in one extremely clear way.

    In other words, Flask is perhaps the best choice for a beginner developer as it contains fewer components. In addition, it is worth choosing if you need to fine-tune your project.

    Flask, due to its flexibility, is better suited for creating REST APIs.

    On the other hand, if your goal is to do something quickly and easily, you should probably choose Django.

    Data Science: Machine Learning, Data Analysis and Visualization

    First of all, you need to figure out what it is.

    Let's say you want to develop a program that will automatically detect what is shown in a picture.

    For example, by presenting it with this image, you want the program to identify the dog.

    And here she should see a table.

    You might be thinking that you can simply write image analysis code to solve this problem. For example, if there are a lot of light brown pixels in the picture, we conclude that it is a dog.

    Or you can learn to identify edges and boundaries in an image. Then a picture with a lot of straight edges will probably be a table.

    However, this is a rather complex and ill-conceived approach. What should you do if the photo shows a white dog with no brown spots? Or if the picture shows a round table?

    This is where machine learning comes into play. Typically it implements some , which allows automatic detection of a familiar pattern among the input data.

    You can feed the machine learning algorithm, say, 1000 pictures of a dog and 1000 pictures of tables. It will learn the difference between these objects. Then, when you give him a new picture of a table or a dog, he will be able to identify what it is.

    • scikit-learn has several popular learning algorithms built-in out of the box;
    • TensorFlow is a lower level library. It allows you to create custom algorithms.

    For those new to machine learning, scikit-learn is a good place to start. More experienced developers who are facing efficiency issues may want to take a closer look at TensorFlow.

    How to study machine learning?

    Real analysts, such as those at Google or Microsoft, do the same thing, only their work is more complex and complex.

    They use the SQL query language to retrieve data from databases. Special tools such as Mathplotlib (for Python) or D3.js (for JavaScript) are then used for analysis and visualization.

    Ways to use Python for data analysis and visualization

    One of the most popular libraries for visualization is Mathplotlib.

    Beginners should start learning with it for two reasons:

    • low entry threshold;
    • mastering Mathplotlib will allow you to quickly understand more complex libraries based on it in the future, for example, seaborn.

    How to learn data analysis in Python?

    Recently, some companies have started using JavaScript to create desktop applications. For example, the Slack desktop app was built using the Electron JavaScript framework.

    The advantage of writing desktop applications in JavaScript is that you can reuse the code from the web version.

    Python 3 or Python 2

    Python 3 is a more modern and popular choice.

    Explanation of backend and frontend code

    Let's say you want to do something reminiscent of Instagram.