The python programming language for dummies. History of the creation of the language. Code readability is key

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

Python - language description given in Foundation describes Python:

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

Which programming language to learn first?

You can start learning Python with a programming language. To illustrate how Python differs from other introductory languages, remember the time when you were a teenager.

Learning programming with Python is like driving a parent minivan. As soon as you make a few laps on it in the parking lot, you will begin to understand how to drive a car.

Trying to learn programming with C ( or even assembler) it's like learning to drive by collecting your parents' minivan. You will be stuck in the garage for several years, putting the parts together, and when you have a full understanding of how the machine works, and will be able to identify malfunctions and predict future problems, you will burn out before you ever get behind the wheel.

Python Benefits

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

General purpose high-level language

Python is a high-level programming language. Using it, you can create almost any type of software. This versatility supports your interest, as you develop programs and solutions focused on your interests, and do not get stuck in the wilds of the language, worrying about its syntax.

Interpreted Language

The Python programming language for beginners is interpretable, which means you don’t need to know how to compile the code. Since there is no compilation stage, productivity increases, and the time for editing, testing, and debugging is significantly reduced. Just download the integrated development environment ( IDE), write your code and click "Run" ( Run).

Code readability is key

Simple, easy-to-learn Python syntax emphasizes readability and defines a good programming style. With Python, you can express your concept with fewer lines of code. This language also makes you think about program logic and algorithms. In this regard, it is often used as a scripting or integrating language ( glue language) to link existing components together and write large volumes of easily readable and workable code in short intervals.

It's just fun

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

... Python requires less time, fewer lines of code and fewer concepts to achieve its goal ... And to top it off, Python programming is fun! Fun and frequent success gives rise to confidence and interest among students who are better prepared for further study of the Python language.

Translation of “Why Learn Python? »Was prepared by a friendly project team.

Good bad

Once upon a time, in one closed forum, I tried to teach Python. In general, the matter died out 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. The rest is more interesting, but maybe it will not be interesting. In general, this post will be a trial ball, if I like it, I will spread it further.

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

Just in case, a little boring "evangelism". To whom he is tired, you can skip a few paragraphs.
  Python (read as “Python” and not “Python”) is a scripting language developed by Guido van Rossum as a simple language that is easy to learn for a beginner.
  Nowadays, Python is a widely spoken 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 Zope Application-server and CMS Plone developed on its basis, on the basis of which the CIA website works, and the mass of frameworks for the rapid development of Plones, Django, TurboGears and many others)
   - Use as an embedded scripting language in many games, and not only (in the office suite OpenOffice.org, 3d editor Blender, DBMS Postgre)
   - Use in scientific calculations (with SciPy and numPy packages for calculations and PyPlot for drawing graphs, Python becomes almost comparable to packages like MatLab)

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

1. The interpreter itself, it can be taken here (http://python.org/download/).
  2. Development environment. It is optional for starters, and the IDLE coming in the distribution kit 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 it will be enough just the interactive shell of Python itself.

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

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

Then the interpreter will wait at the end of the program for pressing enter.

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

Finally, you can use one of the many handy Python IDEs that provide both debugging and syntax highlighting features and many other “amenities”.

A bit of theory.

For starters, Python is a language with strong dynamic typing. What does this mean?

There are languages \u200b\u200bwith strong typing (pascal, java, c, etc.), in which the type of the variable is determined in advance and cannot be changed, and there are languages \u200b\u200bwith dynamic typing (python, ruby, vb) in which the type of the variable is interpreted in depending on the assigned value.
  Languages \u200b\u200bwith dynamic typing can be divided into 2 types. Strict ones that do not allow implicit type conversions (Python) and non-strict ones that perform implicit type conversions (for example, VB, in which you can easily add the string "123" and the number 456).
  Having dealt with the classification of Python, let's try a little "play" with the interpreter.

  \u003e\u003e\u003e a \u003d b \u003d 1 \u003e\u003e\u003e a, b (1, 1) \u003e\u003e\u003e b \u003d 2 \u003e\u003e\u003e a, b (1, 2) \u003e\u003e\u003e a, b \u003d b, a \u003e\u003e\u003e a , b (2, 1)

Thus, we see that assignment is done using the \u003d sign. You can assign a value to several variables at once. When an interpreter is given a variable name interactively, it displays its value.

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

The condition is specified using the if statement, which ends with ":". Alternative conditions that will be met if the first check "failed" are set by the elif operator. Finally else sets the branch that will be executed if none of the conditions match.
  Please note that after entering if, the interpreter, using the “...” prompt, indicates that it expects the input to continue. To tell him that we are done, you must enter an empty line.

  (The branching example somehow breaks the markup on the hub, despite the dances with the tags pre and code. Sorry for the inconvenience, I threw it here pastebin.com/f66af97ba, if someone tells me what is wrong - I will be very grateful)

Cycles.

The simplest case of a loop is a while loop. As a parameter, it accepts a condition and is satisfied until it is true.
  Here is a small example.

  \u003e\u003e\u003e x \u003d 0 \u003e\u003e\u003e while x<=10: ... print x ... x += 1 ... 0 1 2 ........... 10

Please note that since both print x and x + \u003d 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 of other languages. Its syntax is conditionally as follows.

For variable in list:
   teams

The variable will be assigned in turn all the values \u200b\u200bfrom the list (in fact, there may be not only a list, but any other iterator, but we will not bother with this yet).

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

  \u003e\u003e\u003e x \u003d "Hello, Python!" \u003e\u003e\u003e for char in x: ... print char ... H e l ...........!

This way we can expand the string into characters.
  What to do if we need a cycle that repeats a certain number of times? 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 over which we can “walk” with the for statement.

Here are some examples of using the range function that explains the role of its parameters.

  \u003e\u003e\u003e range (10) \u003e\u003e\u003e range (2, 12) \u003e\u003e\u003e range (2, 12, 3) \u003e\u003e\u003e range (12, 2, -2)

And a small example with a loop.

  \u003e\u003e\u003e 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 - this is how I / O is implemented in it.

The print command is used for output, which prints all its arguments in a human-readable form.

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

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

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

That's all 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 the quadratic equation in a general form. Odds are requested from the user.
  3. Create a program for outputting the 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 \u003d 20
  5 x 5 \u003d 25
  And so on.

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

Python Basics for Beginner Programmers

Python is a powerful, high-level, object-oriented programming language created by Guido van Rossum. It has easy-to-use syntax, which makes it an ideal language for those who are trying to learn programming for the first time. To continue acquaintance with the language, you can read Dmitry Zlatopolsky’s book “Python - the basics of programming”. But we will start with the basics. Literature in this area is quite a lot. Another option is Harry Percival's “Python. Test-based development. ” It talks about the language from a practical point of view.

Putting the language into practice

So, what do they write in Python or “Python”, as it is also called among programmers, and why teach it? Python is a general-purpose language. Web applications are written on it using various frameworks, system utilities and applications for automating various actions. Courses on the basics of programming in Python are now enough to try to learn the language yourself.

This could be the foundation 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 well suited for prototyping. That is, first a prototype is created in Python, then the concept can be transferred to faster and more 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 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 in several areas, it will be difficult for you to find a better alternative than Python. It has a number of obvious advantages over other programming languages:

  • universal use - in this language you can write different types of applications, therefore, along with its development, there are great opportunities for using this language;
  • simplicity - initially the language was developed to simplify the work of a person with it;
  • popularity among programmers and demand on 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 - once written, the program will work on any platform where there is a language interpreter;
  • one of the important advantages of the language is its quality documentation.

Python is also one of the oldest web development languages \u200b\u200bcreated by Guido van Rossum at the National Research Institute of Mathematics and Computer Science in the Netherlands in the early 90s. The language is heavily borrowed 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 assume that for the most part they have already mastered the language. It will take some time and you will need to understand the basic concepts before you begin. So let's start by getting to know them.

Python benefits

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 again when the user starts it. Therefore, to run the program, you must have it on the computer where you will create the program. The interpreter and standard library are available in binary or source form from the Python website and can work seamlessly on all major operating systems.

So, the main advantages of Python include:

  • Interpretative: the language is processed by the interpreter at runtime, such as PHP or PERL, so you do not need to compile the program before execution.
  • Interactivity: you can interact directly with the interpreter when writing your program.
  • Ideal for beginners: for beginners.
  • Python is a great choice as 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, choosing 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, it can be started. To do this, at the command prompt, enter: “python”, and it will start. Three angle brackets appear in the window, indicating that you are in the interpreter. This programming language is also freely distributed, and you can find tips, third-party tools, programs, modules, and additional documentation on it.

    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 the interpreter is too time consuming. Therefore, it makes sense to use text editors. The finished text file can then be executed by the interpreter. One of the basics of Python is that any blocks in it are set using indentation, so you must indent to run the 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 marks and has fewer syntactic constructs than other programming languages.

    Getting started with Python

    Before starting work outside the interpreter, to create a program, you need to open a text editor and create an empty utf-8 encoded file and set the extension “py”. It is best to use special code editors for programmers for this purpose. The first line must indicate the encoding. Lines beginning with a # sign 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 an object works, you just need to enter 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 document string.

    How to run a written program

    You must also run the written program on the command line. To do this, write the name of the interpreter and, separated by a space, the name of the file with the program written. When starting the program, you must specify the full path to the file. This is not always easy, since the path can be very long, so it is sometimes easier to change the current directory on the command line and run the interpreter there. To do this, go up to the desired directory, hold down the shift key, right-click on the directory and select the option “open command window” 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, after a space, the name of the file that is in it.

    Language syntax

    The basics of programming with the Python language as an example are not too different from other languages, but variables carry a slightly different meaning. Python has no required characters to complete statements. Any blocks are indented, so you must indent to start the block and delete it. For multiline comments, you must use multiline strings. Values \u200b\u200bare assigned using the “\u003d” sign, and equality testing is performed with two of them “\u003d\u003d”. You can decrease or increase values \u200b\u200busing the \u003d or - \u003d operators with the sum on the right side. This can work with strings and other data types. You can also use several variables in one line.

    Python data types

    Now consider the data types. Python is based on data structures — dictionaries, tuples, and lists. Sets can be found in the set library, which is 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 Python-based arrays can be of any type, and ypes is always zero. Negative numbers start from end to start, and -1 is the last element. Variables can also indicate functions.

    Python strings

    Python strings can use single or double quotes, and you can use quotes of one kind in a string using a different kind. Multiline strings are enclosed in single or triple double quotes. To populate strings with values, you can use the modulo operator (%) and then a tuple. Each% is replaced by a tuple element from left to right, and you can also use dictionary substitutions. Python flow control statements: while, for and if. For branching you need to use “if”. To list through a list, use “for”. Use a range for a list of numbers.

    Python Functions

    The keyword “def” is used to declare functions. Binding another object to a variable removes the old one and replaces immutable types. Optional arguments can be specified in the function declaration after the required arguments, giving them default values. For named arguments, the argument name is assigned a value. Functions can return a tuple, and you can efficiently return multiple values \u200b\u200busing tuple unpacking. 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 refer to the available resources to continue learning this interesting and useful programming language.

    In this collection we have collected the most useful books about the Python programming language, which will help in the study of both beginners and experienced programmers.
      Here you will find materials for creating applications, as well as tutorials that will help you familiarize yourself with the tools, master databases and improve your professional skills.

    Sections:

    For beginners

    The manual is an excellent and internationally recognized introduction to the Python language. She will quickly teach you how to write effective, high-quality code. Suitable for both novice programmers and those who already have experience using other languages. In addition to theory, the book contains tests, exercises and useful illustrations - all that is needed to learn Python 2 and 3. In addition, you will get acquainted with some advanced features of the language that have not yet been mastered by many experts.

    Python is a multi-paradigm cross-platform programming language that has recently become especially popular in the West and in such large companies as Google, Apple and Microsoft. Due to its minimalistic syntax and powerful kernel, it is one of the most productive and well-read PLs in the world.

    After reading this book, you will quickly and in a fascinating way learn the basics of the language, then move on to exception handling, web development, working with SQL, data processing and the Google App Engine. You will also learn how to write applications for Android and much more about the power that Python gives you.

    Another recognized Python book in which you will find 52 specially selected exercises to learn a language. Having examined them, you will understand how the language works, how to write programs correctly and how to fix your own mistakes. The topics covered are:

    • Setting the environment;
    • Code organization
    • Basic math;
    • Variables
    • Lines and text;
    • Interaction with users;
    • Work with files;
    • Loops and logic;
    • Data structures;
    • Software development;
    • Inheritance and composition;
    • Modules, classes, and objects;
    • Packages;
    • Debugging
    • Test automation;
    • Game development;
    • Web development.

    This book is intended for beginners to learn programming. It uses a very standard approach to learning, but a non-standard language 🙂 It is worth noting that this is more of a book about the basics of programming than about Python.

    Python Programming for Beginners is a great place to start. It is a detailed guide written specifically for beginners who want to learn this language. Having become familiar with the basics, you will move on to object-oriented programming and creating CGI scripts for processing web form data, learn how to create graphical applications with a window interface and distribute them to other devices.

    With the help of this tutorial, you can go through all the steps from installing the interpreter to launching and debugging full-fledged applications.

    “Python Crash Course” is a comprehensive narrative of the Python language. In the first half of the book, you will become familiar with basic concepts of the language, such as lists, dictionaries, classes, and loops, and learn how to write clean and well-readable code. In addition, you will learn how to test your programs. In the second half of the book, you will be asked to put knowledge into practice by writing 3 projects: an arcade game like Space Invaders, an application for visualizing data, and a simple web application.

    This is a very handy pocket cheat sheet created for Python 3.4 and 2.7. In it you will find the most necessary information on various aspects of the language. Topics covered:

    • Built-in types of objects;
    • Expressions and syntax for creating and processing objects;
    • Functions and modules;
    • OOP (we have a separate one);
    • Built-in functions, exceptions and attributes;
    • Operator overload methods;
    • Popular modules and extensions;
    • Command line options and development tools;
    • Tips
    • Python SQL Database API.

    A book to learn Python with tons of practical examples.

    Practical examples can be found in our section. For example, read our self-service implementation of the zip function.

    The purpose of this book is to introduce the reader to popular tools and various recommendations for writing code accepted in the open source community. The basics of the Python language are not covered in this book, because it is not about that at all.

    The first part of the book contains a description of various text editors and development environments that can be used to write Python programs, as well as many types of interpreters for various systems. The second part of the book talks about the coding style adopted by the open source community. The third part of the book provides a brief overview of the many libraries for Python that are used in most open source projects.

    The main difference between this book and all other manuals for beginners to learn Python is that in parallel with the study of theoretical material, the reader gets acquainted with the implementation of projects of various games. Thus, the future programmer will be able to better understand how certain features of the language are used in real projects.

    The book covers the basics of both the Python language and programming in general. Great book for the first acquaintance with this language.

    For advanced

    If you want to upgrade to Python 3 or correctly upgrade old code written in Python 2, then this book is for you. And also for you - to transfer a project from Python 2 to Python 3 without pain.

    In the book you will find many practical examples in Python 3.3, each of which is discussed in detail. The topics covered are:

      • Data structures and algorithms;
      • Lines and text;
      • Numbers, dates and times;
      • Iterators and generators;
      • Files and read / write operations;
      • Coding and data processing;
      • Functions
      • Classes and objects;
      • Metaprogramming;
      • Modules and packages;
      • Web programming;
      • Competitiveness;
      • System administration;
      • Testing and debugging;
      • C-extensions.

    As you read this book, you will develop a web application while exploring the practical benefits of development through testing. You will cover topics such as database integration, JS automation tools, NoSQL, web sockets, and asynchronous programming.

    The book details Python 3: data types, operators, conditions, loops, regular expressions, functions, object-oriented programming tools, working with files and directories, and commonly used modules of the standard library. In addition, the book also focuses on the SQLite database, the database access interface, and methods for retrieving data from the Internet.

    The second part of the book is entirely devoted to the PyQt 5 library, which allows you to create applications with a graphical interface in Python. Here, tools for processing signals and events, managing window properties, developing multi-threaded applications are described, the main components (buttons, text fields, lists, tables, menus, toolbars, etc.) are described, their placement inside the window, tools for working with databases data, multimedia, printing documents and exporting them in Adobe PDF format.

    Your Pyhton programs may work, but they may work faster. This practical guide will help you better understand the structure of the language, and you will learn to find bottlenecks in the code and increase the speed of programs working with large amounts of data.

    As the name implies, the purpose of this book is to give the most complete concept to the framework for developing Django web applications. Due to the fact that the book was released in Russian back in 2010, it considers an outdated version of the framework, Django 1.1. But still, the book is recommended for reading, as you can learn the basics of Django in it. And there are practically no good books on this framework in Russian, except for this one.

    Authors Adrian Golovaty and Jacob Kaplan-Moss examine in detail the components of the framework. The book has a lot of material on the development of Internet resources in Django - from the basics to such special topics as PDF and RSS generation, security, caching and internationalization. Before reading the book, it is recommended to master the basic concepts of web development.

    Game development

    Making Games with Python & Pygame is a book dedicated to the Pygame game development library. In each chapter, the full source code of the new game and detailed explanations of the development principles used are given.

    The book "Invent Your Own Computer Games with Python" will teach you how to program in Python using the example of game development. In later games, the creation of two-dimensional games using the Pygame library is considered. You will learn:

    • use loops, variables, and logical expressions
    • use data structures such as lists, dictionaries, and tuples
    • debug programs and look for errors;
    • write a simple AI for games;
    • create simple graphics and animations for your games.

    Data Analysis and Machine Learning

    Boost your skills by working with data structures and algorithms in a new way - scientific. Explore examples of complex systems with clear explanations. The book suggests:

    • learn concepts such as NumPy arrays, SciPy methods, signal processing, fast Fourier transforms and hash tables;
    • get acquainted with abstract models of complex physical systems, fractals and Turing machines;
    • research scientific laws and theories;
    • make out examples of complex tasks.

    In this book, the Python language is considered as a tool for solving problems requiring computation with processing large amounts of data. The purpose of this book is to teach the reader to use the stack of Python data mining tools to efficiently store, manipulate, and understand data.

    Each chapter of the book is dedicated to a specific library for working with big data. The first chapter deals with IPython and Jupyter, the second with NumPy, and the third with Pandas. The fourth chapter contains material about Matplotlib, the fifth - about Scikit-Learn.

    Python for Data Analysis talks about all kinds of data processing methods. The book is an excellent introduction to scientific computing. Here's what you will get to know:

    • iPython interactive shell
    • library for numerical calculations NumPy:
    • pandas data analysis library;
    • library for plotting matplotlib charts.

    You will also learn how to measure data at time intervals and solve analytical problems in many fields of science.

    This book suggests exploring various methods for analyzing data using Python. Here's what you learn after reading:

    • manage data;
    • solve the problems of data science;
    • create high-end visualizations
    • apply linear regressions to evaluate relationships between variables;
    • create recommendation systems;
    • handle big data.

    This manual explains the principles of natural language processing in a clear language. You will learn how to write programs that can process large sets of unstructured texts, gain access to extensive data sets and become familiar with basic algorithms.

    Other

    If you've ever spent hours renaming files or updating hundreds of table cells, then you know how it exhausts. Want to learn how to automate such processes? The book Automate the Boring Stuff with Python talks about how to create programs that will solve a variety of routine tasks in minutes. After reading, you will learn how to automate the following processes:

    • search for specified text in files;
    • creating, updating, moving and renaming files and folders;
    • search and download data on the web;
    • updating and formatting data in Excel tables;
    • separation, merging and encryption of PDF files;
    • distribution of letters and notifications;
    • filling out online forms.

    Great book with a minimum entry threshold. He talks more about biology than about language, but it will definitely come in handy for everyone working in this area. It is supplied with a large number of disassembled examples of varying complexity.

    This book covers the basics of programming a Raspberry Pi system. The author has already compiled many scripts for you, and also provided an intelligible and detailed guide to creating your own. In addition to the usual exercises, you are invited to implement three projects: the game "Hangman", LED-clock and software-controlled robot.

    Hacking Secret Ciphers with Python not only talks about the history of existing ciphers, but also teaches you how to create your own programs for encrypting and breaking ciphers. A great book to learn the basics of cryptography.

    Share useful Python books in the comments!

    Python is a popular and powerful scripting language with which you can do whatever you want. For example, you can scan websites and collect data from them, create network and tools, perform calculations, program for Raspberry Pi, develop graphic programs and even video games. In Python, you can \\\\ write platform-independent system programs.

    In this article we will cover the basics of Python programming, we will try to cover all the basic features that you will need to start using the language. We will consider the use of classes and methods to solve various problems. It is assumed that you are already familiar with the basics and syntax of the language.

    What is Python?

    I will not go into the history of the creation and development of the language, you can easily find out from the video that will be attached below. It is important to note that Python is a scripting language. This means your code is checked for errors and executed immediately without any additional compilation or processing. This approach is also called interpreted.

    This reduces performance, but is very convenient. There is an interpreter in which you can enter commands and immediately see their result. Such interactive work greatly helps in learning.

    Work in the interpreter

    Running the Python interpreter is very simple on any operating system. For example, on Linux, just type the python command in the terminal:

    In the shell prompt that opens, we see the version of Python that is currently in use. Nowadays, two versions of Python 2 and Python 3 are very common. They are both popular, because the first one has developed many programs and libraries, and the second one has more features. Therefore, distributions include both versions. By default, the second version is launched. But if you need version 3, then you need to do:

    It is the third version that will be considered in this article. Now consider the main features of this language.

    String Operations

    Strings in Python are immutable; you cannot change one of the characters in a string. Any change to the content requires a new copy. Open the interpreter and follow the examples below in order to better understand everything written:

    1. String concatenation

    str \u003d "welcome" + "to python"
      print (str)

    2. Multiplication of lines

    str \u003d "Losst" * 2
      print (str)

    3. Combining with transformation

    You can combine a string with a number or a boolean. But for this you need to use the transformation. There is a str () function for this:

    str \u003d "This is a test number" + str (15)
      print (str)

    4. Substring search

    You can find a character or substring using the find method:

    str \u003d "Welcome to the site"
      print (str.find ("site"))

    This method displays the position of the first occurrence of the site substring; if it is found, if nothing is found, the value -1 is returned. The function starts the search with the first character, but you can start with the nth one, for example, 26:

    str \u003d "Welcome to the site site"
      print (str.find ("losst", 26))

    In this option, the function will return -1, because the string was not found.

    5. Getting a substring

    We got the position of the substring we are looking for, and now how to get the substring itself and what is after it? Use this syntax for this. [start: end], just specify two numbers or only the first:

    str \u003d "One two three"
      print (str [: 2])
      print (str)
      print (str)
      print (str [-1])

    The first line will output a substring from the first to the second character, the second - from the second to the end. Please note that the countdown starts from zero. To count in reverse, use a negative number.

    6. Substring replacement

    You can replace part of a string with the replace method:

    str \u003d "This site is about Linux"
      str2 \u003d str.replace ("Linux", "Windows")
      print (str2)

    If there are many occurrences, then only the first can be replaced:

    str \u003d "This is a Linux site and I am subscribed to this site"
      str2 \u003d str.replace ("site", "page", 1)
      print (str2)

    7. Clearing strings

    You can remove extra spaces with the strip function:

    str \u003d "This is a Linux website"
      print (str.strip ())

    You can also remove extra spaces only on the right rstrip or only on the left - lstrip.

    8. Change  case

    There are special functions for changing the case of characters:

    str \u003d "Welcome to Losst"
      print (str.upper ())
      print (str.lower ())

    9. Convert strings

    There are several functions for converting strings to various numeric types, these are int (), float (), long () and others. The int () function converts to an integer, and float () to a floating-point number:

    str \u003d "10"
      str2 \u003d "20"
      print (str + str2)
      print (int (str) + int (str2))

    10. Line Length

    You can use the functions min (), max (), len () to calculate the number of characters in a string:

    str \u003d "Welcome to Losst"
      print (min (str))
      print (max (str))
      print (len (str))

    The first shows the minimum character size, the second shows the maximum, and the third shows the total length of the string.

    11. Rumble

    You can access each character of a string separately with a for loop:

    str \u003d "Welcome to the site"
      for i in range (len (str)):
      print (str [i])

    To limit the loop, we used the len () function. Pay attention to the indentation. Programming in python is based on this, there are no brackets for organizing blocks, only indents.

    Operations with numbers

    Numbers in Python are simple enough to declare or apply in methods. You can create integers or floating point numbers:

    num1 \u003d 15
      num2 \u003d 3.14

    1. Rounding numbers

    You can round a number using the round function, just specify how many characters you need to leave:

    a \u003d 15.5652645
      print (round (a, 2))

    2. Random number generation

    You can get random numbers using the random module:

    import random
      print (random.random ())

    By default, a number is generated from a range of 0.0 to 1.0. But you can set your range:

    import random
      numbers \u003d
      print (random.choice (numbers))

    Date and Time Operations

    The Python programming language has a DateTime module that allows you to perform various operations with date and time:

    import datetime
      cur_date \u003d datetime.datetime.now ()
      print (cur_date)
      print (cur_date.year)
      print (cur_date.day)
      print (cur_date.weekday ())
      print (cur_date.month)
      print (cur_date.time ())

    The example shows how to extract the desired value from the object. You can get the difference between two objects:

    import datetime
      time1 \u003d datetime.datetime.now ()
      time2 \u003d datetime.datetime.now ()
      timediff \u003d time2 - time1
      print (timediff.microseconds)

    You can create date objects with an arbitrary value yourself:

    time1 \u003d datetime.datetime.now ()
      time2 \u003d datetime.timedelta (days \u003d 3)
      time3 \u003d time1 + time2
      print (time3.date ())

    1. Date and time formatting

    The strftime method allows you to change the date and time format depending on the selected standard or the specified format. Here are the basic formatting characters:

    • % a  - day of the week, short name;
    • % A  - day of the week, full name;
    • % w  - day of the week number, from 0 to 6;
    • % d  - day of the month;
    • % b  - the abbreviated name of the month;
    • % B  - full name of the month;
    • % m  - month number;
    • % Y  - year number;
    • % H  - hour of the day in 24 hour format;
    • % l  - hour of the day in 12 hour format;
    • % p  - AM or PM;
    • % M  - minute;
    • % S  - second.

    import datetime
      date1 \u003d datetime.datetime.now ()
      print (date1.strftime ("% d.% B% Y% I:% M% p"))

    2. Create a date from a string

    You can use the strptime () function to create a date object from a string:

    import datetime
      date1 \u003d datetime.datetime.strptime ("2016-11-21", "% Y-% m-% d")
    date2 \u003d datetime.datetime (year \u003d 2015, month \u003d 11, day \u003d 21)
      print (date1);
      print (date2);

    File system operations

    File management is very simple in the Python programming language, it is the best language for working with files. Anyway, we can say that Python is the simplest language.

    1. Copy files

    To copy files, you need to use the functions from the subutil module:

    import shutil
      new_path \u003d shutil.copy ("file1.txt", "file2.txt")

    new_path \u003d shutil.copy ("file1.txt", "file2.txt", follow_symlinks \u003d False)

    2. Moving files

    Files are moved using the move function:

    shutil.move ("file1.txt", "file3.txt")

    The rename function from the os module allows you to rename files:

    import os
      os.rename ("file1.txt", "file3.txt")

    3. Reading and writing text files

    You can use the built-in functions to open files, read or write data to them:

    fd \u003d open ("file1.txt")
      content \u003d fd.read ()
      print (content)

    First you need to open the file to work using the open function. The read function is used to read data from a file, the read text will be saved in a variable. You can specify the number of bytes to read:

    fd \u003d open ("file1.txt")
      content \u003d fd.read (20)
      print (content)

    If the file is too large, you can split it into lines and already do the processing:

    content \u003d fd.readlines ()
      print (content)

    To write data to a file, you must first open it for writing. There are two modes of operation - overwriting and adding to the end of the file. Recording Mode:

    fd \u003d open ("file1.txt", "w")

    And adding to the end of the file:

    fd \u003d open ("file1.txt", "a")
      content \u003d fd.write ("New Content")

    4. Creating directories

    To create a directory, use the mkdir function from the os module:

    import os
      os.mkdir ("./ new folder")

    5. Getting creation time

    You can use the functions getmtime (), getatime () and getctime () to get the time of the last change, last access and creation. The result will be displayed in Unix format, so it must be converted to a readable form:

    import os
      import datetime
      tim \u003d os.path.getctime ("./ file1.txt")
      print (datetime.datetime.fromtimestamp (tim))

    6. File List

    Using the listdir () function, you can get a list of files in a folder:

    import os
      files \u003d os.listdir (".")
      print (files)

    To solve the same problem, you can use the glob module:

    import glob
      files \u003d glob.glob ("*")
      print (files)

    7. Serializing Python Objects

    import pickle
      fd \u003d open ("myfile.pk", "wb")
      pickle.dump (mydata, fd)

    Then, to restore the object, use:

    import pickle
      fd \u003d open ("myfile.pk", "rb")
      mydata \u003d pickle.load (fd)

    8. File Compression

    The Python standard library allows you to work with various archive formats, for example, zip, tar, gzip, bzip2. To view the contents of a file use:

    import zipfile
      my_zip \u003d zipfile.ZipFile ("my_file.zip", mode \u003d "r")
      print (file.namelist ())

    And to create a zip archive:

    import zipfile
      file \u003d zipfile.ZipFile ("files.zip", "w")
      file.write ("file1.txt")
      file.close ()

    You can also unzip the archive:

    import zipfile
      file \u003d zipfile.ZipFile ("files.zip", "r")
      file.extractall ()
      file.close ()

    You can add files to the archive like this:

    import zipfile
      file \u003d zipfile.ZipFile ("files.zip", "a")
      file.write ("file2.txt")
      file.close ()

    9. Analysis of CSV and Exel files

    Using the pandas module, you can view and parse the contents of CSV and Exel tables. First you need to install the module using pip:

    sudo pip install pandas

    Then to parse, type:

    import pandas
      data \u003d pandas.read_csv ("file.csv)

    By default, pandas uses the first column for the headers of each line. You can specify a column for the index using the index_col parameter or specify False if it is not needed. To write changes to a file, use the to_csv function:

    data.to_csv ("file.csv)

    In the same way, you can parse the Exel file:

    data \u003d pd.read_excel ("file.xls", sheetname \u003d "Sheet1")

    If you need to open all tables, use:

    data \u003d pd.ExcelFile ("file.xls")

    Then you can write all the data back:

    data.to_excel ("file.xls", sheet \u003d "Sheet1")

    Networking in Python

    Python 3 programming often involves networking. The Python standard library includes sockets for low-level network access. This is necessary to support many network protocols.

    import socket
      host \u003d "192.168.1.5"
      port \u003d 4040
      my_sock \u003d socket.create_connection ((host, port))

    This code connects to port 4040 on machine 192.168.1.5. When the socket is open, you can send and receive data:

    my_sock.sendall (b "Hello World")

    We need to write the character b, before the line, because we need to transfer data in binary mode. If the message is too large, you can iterate:

    msg \u003d b "Longer Message Goes Here"
      mesglen \u003d len (msg)
      total \u003d 0
      while total< msglen:
      sent \u003d my_sock.send (msg)
      total \u003d total + sent

    To get the data, you also need to open the socket, only the my_sock_recv method is used:

    data_in \u003d my_sock.recv (2000)

    Here we indicate how much data you need to get - 20,000, the data will not be transferred to the variable until 20,000 bytes of data are received. If the message is larger, then to receive it you need to create a loop:

    buffer \u003d bytearray (b "" * 2000)
      my_sock.recv_into (buffer)

    If the buffer is empty, the received message will be written there.

    Work with mail

    The Python standard library allows you to receive and send emails.

    1. Receiving mail from a POP3 server

    To receive messages, we use the POP server:

    import getpass, poplib
      pop_serv \u003d poplib.POP3 ("192.168.1.5")
      pop_serv.user ("myuser")
      pop_serv.pass_ (getpass.getpass ())

    The getpass module allows you to retrieve the user's password in a secure manner, so that it will not be displayed on the screen. If the POP server uses a secure connection, you need to use the POP3_SSL class. If the connection is successful, you can interact with the server:

    msg_list \u003d pop_serv.list () # to list the messages
      msg_count \u003d pop_serv.msg_count ()

    To complete the work, use:

    2. Receiving mail from an IMAP server

    To connect and work with the IMAP server, the imaplib module is used:

    import imaplib, getpass
      my_imap \u003d imaplib.IMAP4 ("imap.server.com")
      my_imap.login ("myuser", getpass.getpass ())

    If your IMAP server uses a secure connection, you must use the IMAP4_SSL class. For a list of messages, use:

    data \u003d my_imap.search (None, "ALL")

    Then you can cycle through the selected list and read each message:

    msg \u003d my_imap.fetch (email_id, "(RFC822)")

    But, do not forget to close the connection:

    my_imap.close ()
      my_imap.logout ()

    3. Sending mail

    To send mail, the SMTP protocol and the smtplib module are used:

    import smtplib, getpass
      my_smtp \u003d smtplib.SMTP (smtp.server.com ")
      my_smtp.login ("myuser", getpass.getpass ())

    As before, use SMTP_SSL for a secure connection. When the connection is established, you can send a message:

    from_addr \u003d " [email protected]"
      to_addr \u003d " [email protected]"
      msg \u003d "From: [email protected]\\ r \\ nTo: [email protected]\\ r \\ n \\ r \\ nHello, this is a test message "
      my_smtp.sendmail (from_addr, to_addr, msg)

    Work with web pages

    Python programming is often used to write various scripts for working with the web.

    1. Web crawling

    The urllib module allows you to query web pages in a variety of ways. To send a regular request, the request class is used. For example, we execute a regular page request:

    import urllib.request
      my_web \u003d urllib.request.urlopen ("https://www.google.com")
      print (my_web.read ())

    2. Using the POST method

    If you need to submit a web form, you need to use not a GET request, but a POST:

    import urllib.request
      mydata \u003d b "Your Data Goes Here"
      my_req \u003d urllib.request.Request ("http: // localhost", data \u003d mydata, method \u003d "POST")
    my_form \u003d urllib.request.urlopen (my_req)
      print (my_form.status)

    3. Creating a web server

    Using the Socket class, you can accept incoming connections, which means you can create a web server with minimal features:

    import socket
      host \u003d ""
      port \u003d 4242
      my_server \u003d socket.socket (socket.AF_INET, socket.SOCK_STREAM)
      my_server.bind ((host, port))
      my_server.listen (1)

    When the server is created. you can start accepting connections:

    addr \u003d my_server.accept ()
      print ("Connected from host", addr)
      data \u003d conn.recv (1024)

    And don't forget to close the connection:

    Multithreading

    Like most modern languages, Python allows you to run several parallel threads, which can be useful if you need to perform complex calculations. The standard library has a threading module that contains the Therad class:

    import threading
      def print_message ():
      print ("The message got printed from a different thread")
      my_thread \u003d threading.Thread (target \u003d print_message)
      my_thread.start ()

    If the function works for too long, you can check if everything is in order using the is_alive () function. Sometimes your threads need to access global resources. For this, locks are used:

    import threading
      num \u003d 1
      my_lock \u003d threading.Lock ()
      def my_func ():
      global num, my_lock
      my_lock.acquire ()
      sum \u003d num + 1
      print (sum)
      my_lock.release ()
      my_thread \u003d threading.Thread (target \u003d my_func)
      my_thread.start ()

    findings

    In this article, we covered the basics of python programming. Now you know most of the commonly used functions and can use them in your small programs. You will love programming in Python 3, it is very easy! If you have any questions, ask in the comments!

    At the end of the article, a great lecture on Python:

    Do you like the article? To share with friends: