The python language. How can you learn machine learning? How to run a written program

Python is a powerful and easy-to-learn programming language. It provides convenient high-level data structures and a simple yet effective approach to object-oriented programming. Python interpreted language. The CPython interpreter is required to run the written programs. The python interpreter and large standard library are freely available as source and binaries for all major platforms on the official website Python http://www.python.org and may be redistributed without restriction. In addition, the site contains distributions and links to numerous third party modules and detailed documentation.
The language has a clear and consistent syntax, well thought-out modularity and scalability, due to which the source code written in Python programs are easy to read. Language Developers Python adhere to a specific programming philosophy called "The Zen of Python". Its text is issued by the interpreter by the import this command:

\u003e\u003e\u003e import this The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren "t special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one - -obvious way to do it. Although that way may not be obvious at first unless you "re Dutch. Now is better than never. Although never is often better than * right * now. If the implementation is hard to explain, it "s a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea - let" s do more of those!

Translated, it sounds like this:

  • Beautiful is better than ugly.
  • Explicit is better than implicit.
  • Simple is better than complex.
  • Complex is better than confusing.
  • Flat is better than nested.
  • Sparse is better than dense.
  • Readability matters.
  • Special cases are not special enough to break the rules.
  • At the same time, practicality is more important than perfection.
  • Errors should never be hushed up.
  • If not explicitly hushed up.
  • When faced with ambiguity, drop the temptation to guess.
  • There must be one - and preferably only one - obvious way to do this.
  • Although it may not be obvious at first, unless you are Dutch.
  • Now is better than ever.
  • Although never is often better than right now.
  • If the implementation is difficult to explain, the idea is bad.
  • If the implementation is easy to explain, the idea is probably good.
  • Namespaces are great! We will make more of them!

Python is an actively developing programming language, new versions are released approximately every two and a half years. As a result of this and some other reasons for Python there is no ANSI, ISO or other official standards, their role is played by CPython.

History of the creation of the language

Development of the Python language was started in the late 1980s by an employee of the Dutch CWI. The Amoeba distributed OS required an extensible scripting language for which Guido van Rossum created Python. New language borrowed some developments for the ABC language, which was focused on teaching programming. In February 1991, Guido published the source text on the alt.sources newsgroup. The name of the language did not come from the species of reptiles. The author named the language after the popular 1970s British comedy television show, Monty Python's Flying Circus. Nevertheless, the emblem of the language is represented by snake heads. After extensive testing, the first version of Python 3.0 was released. Both development branches (Python 3.x and 2.x) are currently supported.

Python was created under the influence of many programming languages: Modula-3, С, C ++, Smalltalk, Lisp, Fortran, Java, Miranda, Icon. Despite the fact that Python has a rather distinctive syntax, one of the design principles of this language is the principle of least surprise.

Standard library

The rich standard library is one of the cool things about Python. There are tools here to work with many network protocols and Internet formats. There are modules for working with regular expressions, text encodings, multimedia formats, cryptographic protocols, archives. In addition to the standard library, there are many libraries that provide an interface to all system calls on different platforms.
For Python, the specification of the programming interface to databases DB-API 2 has been adopted, and packages corresponding to this specification have been developed for accessing various DBMS: Oracle, MySQL, PostgreSQL, Sybase, Firebird (Interbase), Informix, Microsoft SQL Server and SQLite.
The NumPy library for working with multidimensional arrays allows you to achieve scientific computing performance comparable to specialized packages. SciPy uses NumPy and provides access to a wide range of mathematical algorithms. Numarray is specially designed for operations with large amounts of scientific data.
Python provides a simple and convenient C API for writing your own modules in C and C ++. A tool like SWIG allows you to almost automatically get bindings for using C / C ++ libraries in your Python code. The ctypes standard library tool allows Python programs to directly access dynamic libraries written in C. There are modules that allow you to embed C / C ++ code directly into source files Python by building extensions on the fly.
Python and the vast majority of libraries for it are free and shipped in source codes... Moreover, unlike many open systems, the license does not restrict the use of Python in commercial development in any way and does not impose any obligations other than copyright notice.

Applications

Python is a stable and widespread language. It is used in many projects and in various capacities: as a primary programming language or for building extensions and application integrations. A large number of projects have been implemented in Python, and it is also actively used to create prototypes of future programs. Python is used by many large companies.
Python with packages NumPy, SciPy and MatPlotLib is actively used as a universal environment for scientific calculations as a replacement for the widespread specialized commercial packages Matlab, IDL, etc.
IN professional programs 3D graphics such as Houdini and Nuke, Python is used to extend standard features programs.

Sources

Presentations

Homework

Prepare messages:

  • Python as a tool for scientists
  • Python and Ruby (comparison)
  • Python and WEB
  • Creating windowed applications using Python and graphics libraries (wxPython, PyQt, PyGTK, etc.)

It is worth learning the language python programming? After all, you can often hear that this language is dying. This question was discussed by users of the Quora website and shared their opinions.

Bill Karwn, SQL Developer, Consultant, Trainer and Author

Assembly language gives you the perfect opportunity to write compact, efficient, and project-optimized code. You can do amazing things in code written in this language, which is only a few kilobytes long. But the level of efficiency that can be obtained using assembly language does not justify the extra work, the extra time, and the skills it requires.

It is true that languages \u200b\u200bboth gain in popularity and lose it. Productivity is a major challenge in programming, so from time to time new languages \u200b\u200bare created that increase productivity, at least for some jobs.

Most programmers today use higher-level languages \u200b\u200b- they need to be more productive. Languages top level can be compiled into machine code (C or C ++), or can be compiled into bytecode with an independent architecture and run in virtual machine (Java) or be processed (JavaScript, PHP, Ruby, Python, Perl, etc.).

It is a misconception that it is necessary to learn assembly language because "it is better than Python". This is a silly point of view based on outdated data.

Bill Poucher, CEO of ICPC, software for energy, synthetic genetics, and more

Learn Python. Provide yourself with programming experience. This language has its own elegance.

Learn C as a language for Unix machines. Understanding UNIX is relatively straightforward.

Learn MIX to understand Knuth.

Learn Java so you don't have difficulty working with others, as well as master object-oriented programming.

Learn C ++ so you can program in any style you want. Its strength is that it is the main programming language. Its weakness is that you need to understand its style to program in it.

Learn LISP to solidify your understanding of recursion.

Did I say that you shouldn't learn at least something? No. Because the only thing that needs to be done is to accustom yourself to constantly learning something, especially learning how to solve the problems that arise.

Shiva Shinde, Python is easy to code but hard to read

The Python programming language is not dying, it is one of the fastest growing languages.

  1. It's easy to learn
  • Currently, 8 of the top 10 American computing programs use this language (Philip Guo, CACM)
  • Python programs tend to have a minimum of patterns that are commonly found in other programming languages. Therefore, you can use unconventional problem solutions more often.
  • If you have programming experience, even if not in this language, then you will quickly master Python.

2. Full functionality

  • It is not only a language for statistics. Python has all the capabilities for collecting and cleaning data, for working with databases and high performance computing, and much more.
  • This is a generally accepted programming language with a huge number of built-in libraries. It is good for data and database management, as well as for working with network programming. It is a thoughtful language with a wealth of resources available.

3. Serious scientific data libraries

  • Python has significant scientific libraries with a huge amount of data to use.
  • The basis of these scientific libraries is SciPy Ecosystem, which even hosts its own conferences.
  • Pandas and Matplotlib are both part of SciPy. They provide excellent data on a wide variety of topics, such as machine learning, intelligent analysis text and network analysis.

Hernan Soulages, pragmatic programmer

This language is quite popular, its importance is growing in academic circles. It is also true that the usefulness of a programming language depends on what you want to do in it.

I don't like PHP at all, but I’m not stupid enough to deny its versatility and power, and that the language is easy enough to master.
As for learning assembler, this language directly depends on what processor you are working with.

If you know how to work with one, then you will definitely be able to use it in a processor family for some time. But over time, they also undergo some changes. In this sense, it is the least durable language family.

Magnus Lychka, developer software and consultant in Gothenburg

Many users like Python. For some applications, it will be too slow, and, for example, with assembly language, they will run faster, but also quickly these applications will run in C, while the code written in C will work for all platforms.

Many startups became successful with the Python language, after which they had to rewrite some programs in Java, C ++ or C. the quick but hard-to-read code would be complete.

But when working with assembly language, you will have to deal not only with different processor architectures, but also with technical details that differ in different operating systems.

A step-by-step guide for anyone who wants to learn Python programming (or programming in general) but doesn't know where to take the first step.

What to do?

We've looked at a lot of tutorials and just good articles, and we've compiled a list of what you need to learn to master and grow with this programming language.

1. Learn the basics first. Learn what variables, control structures, data structures are. This knowledge is required without reference to a specific language.

2. Take up the study of literature. Start with the classic - Dive into Python. This book can generally become a desktop. You can also read Michael Dawson "Programming in Python" and Alexei Vasiliev "Python by examples. Practical course on programming ". Dawson is an experienced programmer and teacher, and in the book he teaches programming by creating simple games... In contrast, Vasiliev's book pays more attention to the basics and theory.

4. Take the MIT Introduction to Computing and Python Programming course.

5. Find out what libraries and for what purposes other pythonists are using. Find something interesting for yourself.

6. If you are interested in web technologies, take a look at the Flask and Django frameworks. Find out for what purpose which one is best suited, start exploring the one that suits you.

7. Learn how to get and analyze data sets from individual sites, from all over the Internet and anywhere else - just try to stay within the law.

8. Look for information on machine learning techniques.

9. Streamline your work with tools, automate routine and anything that is not yet automated.

Where to go?

Several useful links to resources that will help you Google a little less and decide in which direction to work.

Useful Resources

Python Tutor

This tool helps to cross a fundamental barrier to understanding the programming language you are learning: by visualizing the code, this resource will provide an understanding of what happens when the computer executes each line of code.

Bucky Roberts on YouTube

If you are not familiar with programming, these tutorials will help you a lot. They are easy to understand and cover everything that might come in handy at first, starting with installing the language.

Derek Banas on YouTube on Python

Derek is a self-taught programmer, and he has his own view of the approach to learning programming languages. He makes short video reviews in various languages, 40-60 minutes long, in which he tells everything you need to in order to understand the purpose of the language in general terms.

Corey Schafer on YouTube

Corey good videos on string formatting, generators, programming terms (combinations and permutations, DRY, closures), and more to help you understand basic concepts.

Django Getting Started

The official documentation for the Django web framework. Covers everything you need to know first, from installation to first app.

Introduction to Flask

A video course on YouTube for those who want to get acquainted with Flask, understand some of its subtleties and find out why it is needed at all.

useful links

Newbie

Python 3 for beginners
"A Byte of Python"

Python is a popular and powerful scripting language with which you can do whatever you want. For example, you can crawl and collect data from websites, build networking and tools, perform calculations, program for the Raspberry Pi, develop graphics programs, and even video games. In Python you can write \\\\ system programsplatform independent.

In this article we will cover the basics of Python programming, we will try to cover all the basic features that you need to start using the language. We will look at using 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's 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 rework. This approach is also called interpreted.

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

Working in the interpreter

It is very easy to start the Python interpreter in any operating system... For example, on Linux, just type the python command in the terminal:

In the interpreter 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 widespread. They are both popular because many programs and libraries were developed on the first, and the second has more features. Therefore, distributions include both versions. The second version starts by default. But if you need version 3, then you need to run:

It is the third version that will be considered in this article. Now let's look at 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 an interpreter and follow the examples below to get a better understanding of what you have written:

1. Concatenation of strings

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

2. Multiplication of strings

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

3. Combine with transformation

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

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

4. Search for a substring

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 searching at the first character, but you can start at the nth character, for example, 26:

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

In this case, 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? To do this, use this syntax [start: end], just specify two numbers or just the first:

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

The first line will print the substring from the first to the second character, the second - from the second to the end. Note that the countdown starts at zero. To count down, use a negative number.

6. Substring replacement

You can replace part of a string using 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 lines

You can remove extra whitespace with the strip function:

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

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

8. Changing the register

There are special functions to change the case of characters:

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

9. Converting strings

There are several functions for converting a string to various numeric types, these are int (), float (), long () and others. The int () function converts to an integer, and float () converts 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 min (), max (), len () functions to calculate the number of characters in a string:

str \u003d "Welcome to Losst website"
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. Loop over the line

You can access each character of the 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. Python programming is based on this, there are no parentheses to organize blocks, only indentation.

Operations with numbers

Numbers in Python are simple enough to declare or use 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 to leave:

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

2. Generation of random numbers

Get random numbers using the random module:

import random
print (random.random ())

By default, the number is generated from the range 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 on 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 an 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 yourself with an arbitrary value:

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

1. Formatting date and time

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

  • % a - day of the week, abbreviated name;
  • % A - day of the week, full name;
  • % w - number of the day of the week, from 0 to 6;
  • % d - day of the month;
  • % b - abbreviated name of the month;
  • % B - full name of the month;
  • % m - month number;
  • % Y - number of the year;
  • % 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 date from 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 easy in the Python programming language, it is best language to work with files. Anyway, we can say that Python is the simplest language.

1. Copying files

To copy files, you need to use 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

Moving files is done 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 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 with the open function. To read data from a file, use the read function, the read text will be saved to 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 do the processing like this:

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

To write data to a file, you first need to open it for writing. There are two modes of operation - overwrite and append 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 the creation time

You can use the getmtime (), getatime () and getctime () functions to get the last modified, last accessed and created times. The result will be displayed in Unix format, so you need to convert it to a readable form:

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

6. File list

With the listdir () function, you can list the files in a folder:

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

The glob module can be used to accomplish the same task:

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

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 unpack 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. Parsing 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 headings of each row. You can set the column for the index using the index_col parameter, or specify False if not needed. To write changes to a file use the to_csv function:

data.to_csv ("file.csv)

Exel file can be parsed in the same way:

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 socket capabilities 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 the 192.168.1.5 machine. 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 string, because we need to transfer data in binary mode. If the post is too big, 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 receive data, you also need to open a socket, only the my_sock_recv method is used:

data_in \u003d my_sock.recv (2000)

Here we indicate how much data needs to be received - 20,000, the data will not be transferred to a variable until 20,000 bytes of data have been 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.

Working with mail

The Python Standard Library allows you to receive and send email messages.

1. Receiving mail from POP3 server

We use a POP server to receive messages:

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 securely retrieve the user's password 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 was 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 the 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. To get a list of messages use:

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

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

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

But don't forget to close the connection:

my_imap.close ()
my_imap.logout ()

3. Sending mail

The SMTP protocol and the smtplib module are used to send mail:

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)

Working with web pages

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

1. Web crawling

Urllib module allows you to make requests to web pages different ways... The request class is used to send a regular request. For example, let's execute a normal 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 a POST rather than a GET request:

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

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 multiple parallel threads, which can be useful if you need to perform complex calculations. IN standard library there is 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 takes too long, you can check if everything is in order with 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 ()

conclusions

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

To conclude this article with a great lecture on Python:

A couple of decades ago, programmers seemed like some kind of shamans who knew what was inaccessible to others. Sometimes people learned programming on their knees, scribbling a code on a piece of paper, because the "concentration of computer devices per capita" was extremely low. Now it is difficult to find a person who does not have a home stationary computer or laptop. Learning technologies are also moving forward.

A bit of history

The Python programming language was first developed by Guido van Rossum in the late eighties. Guido was a fellow at the Dutch CWI at the time. He wrote this language at his leisure, putting in some ideas on the ABC language, in the work on which he participated.

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

It's not just van Rossum's design intuition that is considered the reason why the Python programming language is so popular. Learning from scratch becomes enjoyable and easy when you consider the presence of a friendly community of users.

Not so long ago, in 2008, the first, previously long-tested version of Python 3000 (3.0) was released, where many of the architecture flaws were eliminated. At the same time, the developers have tried to maintain compatibility with previous versions of the language. Despite the availability of a more recent version, both branches (2.x and 3.x) are supported.

Laconic programming language

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

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

Diffidence

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

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

Introductory course

Let's remember primary school... As a rule, even a child comes to the first grade with some minimal knowledge: his parents worked with someone, someone went to zero. The same goes for training in the Python programming language. It is really convenient and "transparent", but without minimal knowledge about basic principles action training programs will go hard. It's like learning notes without hearing the music. Therefore, those who have never dealt with programming at all should familiarize themselves with the "introductory minimum".

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

In the Internet

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

Communication on the forums is also important. Learning alone is always more difficult, so don't neglect the different communities.

Paid courses

You can always use paid courses, but sometimes it costs a lot of money, and the result may be unsatisfactory. Therefore, it is of course advisable to choose courses that offer a free orientation assignment. For example, there is an intensive course on "Fundamentals of Python Programming" at GeekBrains. The lesson is free, held every ten days. To sign up, you need to log in to the site.

Tip: Whichever course you choose, first familiarize yourself with the basics of the language, so as not to waste time on what you can easily learn yourself. It will be enough to read the above books.

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

Using

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

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

How to get started

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

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

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

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

print ("Hello world!")

Enter this code in the IDLE window and press Enter. The environment will instantly respond with an action - it will display the required text on the screen. The first program is ready.

Did you like the article? To share with friends: