How to set up smartphones and PCs. Informational portal
  • home
  • Programs
  • Python language. Python for machine learning

Python language. Python for machine learning

The program is a set of algorithms that ensure the execution of the necessary actions. Conventionally, in the same way, you can program an ordinary person by writing precise commands in order, for example, to make tea. If the latter option uses natural speech (Russian, Ukrainian, English, Korean, etc.), then a special programming language will be needed for the computer. Python is one of those. The programming environment will subsequently translate the commands into and the person's purpose for which the algorithm was created will be fulfilled. Python has its own syntax, which will be discussed below.

History of the language

Development began in the 1980s and ended in 1991. The Python language was created by Guido van Rossum. Although the main symbol of "Python" is the snake, it was named after the American comedy show.

When creating the language, the developer used some commands borrowed from existing Pascal, C and C ++. After the first official version went online, a whole group of programmers joined in to refine and improve it.

One of the factors that allowed Python to become quite famous is design. He is recognized as one of the best by many highly successful specialists.

Features of "Python"

The Python programming language for beginners is a great teacher. It has a fairly simple syntax. It will be easy to understand the code, because it does not include many auxiliary elements, and the special structure of the language will teach you how to indent. Of course, a well-designed program with few commands will be immediately understandable.

Many syntax systems have been built around object-oriented programming. Python is no exception. For what exactly was he born? It will facilitate training for beginners, help to remember some of the elements of already qualified employees.

Language syntax

As already mentioned, the code is easy and simple to read. "Python" has sequential commands that are distinguished by the clarity of execution. In principle, the operators used will not seem difficult even for beginners. This is what makes Python different. Its syntax is light and simple.

Traditional operators:

  • When setting a condition, use the if-else construction. If there are too many such lines, you can enter the elif command.
  • Class is for understanding the class.
  • One of the simpler operators is pass. It doesn't do anything, it fits for empty blocks.
  • Loop commands are while and for.
  • Function, method and generator are defined thanks to def.

In addition to single words, the Python programming language allows you to use expressions as operators. By using string chaining, you can reduce the number of individual commands and parentheses. The so-called lazy calculations are also used, that is, those that are performed only when the condition requires it. These include and and or.

The process of writing programs

The interpreter works on a single mechanism: when writing a line (after which "Enter" is placed), it is immediately executed, and a person can already see some result. This is useful and convenient enough for beginners or those who want to test a small piece of code. In compiled environments, you would first have to write the entire program, only then run it and check for errors.

The Python programming language (for beginners, as it has already become clear, it is ideal) in the Linux operating system allows you to work directly in the console itself. You should write the name of the code "Python" in English on the command line. It won't be difficult to create your first program. First of all, it should be borne in mind that you can use the interpreter here as a calculator. Since young and novice specialists are often not friendly with syntax, the algorithm can be written as follows:

After each line it is necessary to put "Enter". The answer will be displayed immediately after clicking it.

Data used by Python

There are several types of data used by computers (and programming languages), and this is quite obvious. Numbers can be fractional, whole, can consist of many digits, or be quite massive because of the fractional part. To make it easier for the interpreter to work with them, and he can understand what he is dealing with, a specific type should be set. Moreover, it is necessary so that the numbers fit into the allotted memory cell.

The most common data types used by the Python programming language are:

  • Integer. We are talking about whole numbers that have both negative and positive values. Zero is also included in this type.
  • In order for the interpreter to understand that it is working with fractional parts, the type should be set to float point. As a rule, it is used in the case of using numbers with a varying point. It should be remembered that when writing a program, you must adhere to the notation "3.25", and not use the comma "3.25".
  • In the case of adding strings, the Python programming language allows you to add the string type. Often, words or phrases are enclosed in single or

Disadvantages and Benefits

In the past few decades, people have been more interested in how to spend more time mastering the data and less time getting it to be processed by the computer. A language about which there are only positives is the highest code.

There are practically no flaws in Python. The only serious drawback is the slowness of the algorithm execution. Yes, if you compare him with "C" or "Java", he is, frankly, a turtle. This is explained by the fact that this

The developer has taken care of adding the best in Python. Therefore, when using it, you will notice that it has absorbed the best features of other higher programming languages.

In the event that the idea implemented by the interpreter is not impressive, then it will be possible to understand this almost immediately, after writing several dozen lines. If the program is good, then the critical section can be improved at any time.

Nowadays, more than one group of programmers is working on improving Python, so it is not a fact that the code written in C ++ will be better than the one created using Python.

Which version is best to work with?

Now two versions of such a syntax system as the Python language are widely used at once. For beginners, the choice between them will be difficult enough. It should be noted that 3.x is still under development (although released to the masses), while 2.x is a fully finalized version. Many people advise using 2.7.8, as it practically does not lag and does not get confused. There are no radical changes in the 3.x version, so at any time your code can be transferred to the programming environment with an update. To download the required program, you should go to the official website, select your operating system and wait until the download is complete.

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. You can \\ write platform-independent system programs in Python.

In this article we will go over the basics of programming in Python, 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 slows down performance, but is very convenient. There is an interpreter here, into which you can enter commands and immediately see their result. This interactive work is very helpful in learning.

Working in the interpreter

It is very easy to start the Python interpreter on any operating system. For example, on Linux, it is enough to 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 is launched by default. But if you need version 3, then you need to execute:

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 the creation of 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 = "welcome" + "to python"
print (str)

2. Multiplication of strings

str = "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 = "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 = "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, then 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 = "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 = "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 = "This site is about Linux"
str2 = str.replace ("Linux", "Windows")
print (str2)

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

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

7. Clearing lines

You can remove extra whitespace with the strip function:

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

It is also possible to remove extra spaces only 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 = "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 () to a floating point number:

str = "10"
str2 = "20"
print (str + str2)
print (int (str) + int (str2))

10. Length of lines

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

str = "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 = "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 easy enough to declare or use in methods. You can create integers or floating point numbers:

num1 = 15
num2 = 3.14

1. Rounding numbers

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

a = 15.5652645
print (round (a, 2))

2. Generation of random numbers

You can get random numbers using the random module:

import random
print (random.random ())

By default, the number is generated in the range 0.0 to 1.0. But you can set your range:

import random
numbers =
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 = 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 = datetime.datetime.now ()
time2 = datetime.datetime.now ()
timediff = time2 - time1
print (timediff.microseconds)

You can create date objects yourself with an arbitrary value:

time1 = datetime.datetime.now ()
time2 = datetime.timedelta (days = 3)
time3 = 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- number of the month;
  • % 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 = 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 = datetime.datetime.strptime ("2016-11-21", "% Y-% m-% d")
date2 = datetime.datetime (year = 2015, month = 11, day = 21)
print (date1);
print (date2);

File system operations

File management is very easy 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. Copying files

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

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

new_path = shutil.copy ("file1.txt", "file2.txt", follow_symlinks = 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 the built-in functions to open files, read or write data to them:

fd = open ("file1.txt")
content = 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 = open ("file1.txt")
content = fd.read (20)
print (content)

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

content = 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 = open ("file1.txt", "w")

And adding to the end of the file:

fd = open ("file1.txt", "a")
content = 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 = os.path.getctime ("./ file1.txt")
print (datetime.datetime.fromtimestamp (tim))

6. List of files

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

import os
files = os.listdir (".")
print (files)

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

import glob
files = glob.glob ("*")
print (files)

7. Serializing Python Objects

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

Then to restore the object use:

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

8. Compressing files

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

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

And to create a zip archive:

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

You can also unpack the archive:

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

You can add files to the archive like this:

import zipfile
file = 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 = pandas.read_csv ("file.csv)

By default, pandas uses the first column for the headings of each row. You can specify 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 = pd.read_excel ("file.xls", sheetname = "Sheet1")

If you need to open all tables, use:

data = pd.ExcelFile ("file.xls")

Then you can write all the data back:

data.to_excel ("file.xls", sheet = "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 = "192.168.1.5"
port = 4040
my_sock = 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 = b "Longer Message Goes Here"
mesglen = len (msg)
total = 0
while total< msglen:
sent = my_sock.send (msg)
total = total + sent

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

data_in = 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 = 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 = 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 = pop_serv.list () # to list the messages
msg_count = 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 = imaplib.IMAP4 ("imap.server.com")
my_imap.login ("myuser", getpass.getpass ())

If your IMAP server uses a secure connection, you need to use the IMAP4_SSL class. To get a list of messages use:

data = my_imap.search (None, "ALL")

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

msg = my_imap.fetch (email_id, "(RFC822)")

But don't 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 = 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 = " [email protected]"
to_addr = " [email protected]"
msg = "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

The urllib module allows you to make requests to web pages in a variety of 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 = 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 = b "Your Data Goes Here"
my_req = urllib.request.Request ("http: // localhost", data = mydata, method = "POST")
my_form = 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 = ""
port = 4242
my_server = 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 = my_server.accept ()
print ("Connected from host", addr)
data = 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. 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 = threading.Thread (target = 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 = 1
my_lock = threading.Lock ()
def my_func ():
global num, my_lock
my_lock.acquire ()
sum = num + 1
print (sum)
my_lock.release ()
my_thread = threading.Thread (target = 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:

Want to get into the programming world and quickly write your first few programs? Or are you dreaming of learning new languages ​​but don't know where to start? Take a look at courses on the basics of Python programming. Read on for details on why this particular language is recommended for beginners and what programs you can create with it.

Python Fundamentals for Beginner Programmers

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

Using the language in practice

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

This could be the backbone 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 also works well 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 algorithms 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 algorithms and programming in Python allows you to quickly create a program and run it. If you need a language to quickly build applications and scripts in multiple areas, you will have a hard time finding a better alternative than Python. It has a number of obvious advantages over other programming languages:

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

Python is also one of the oldest web development languages ​​created by Guido van Rossum at the National Research Institute 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, which make up a lot of Python programming. If you master them, then you can assume that for the most part you have already mastered the language. This will take some time and you will need to understand the basic concepts before starting. So let's start by getting to know them.

Benefits of Python

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

So, the main advantages of Python include:

  • Interpreting nature: The language is processed by an interpreter at runtime, such as PHP or PERL, so you don't need to compile the program before execution.
  • Interactivity: You can interact directly with the interpreter when you write your program.
  • Ideal for beginners: For beginner programmers.
  • 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 the third. It's best to start learning the basics of Python 3 if you haven't installed a different 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. Once installed, you can run it. To do this, on the command line, you need to 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 redistributable, and you can find tips, third-party tools, programs, modules and additional documentation for 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 indented, so you need to 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 acts 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 outside the interpreter, to create a program, you need to open a text editor and create an empty file with utf-8 encoding and set the extension “py”. It is best to use special code editors for programmers for this purpose. In the first line, you need to indicate the encoding. Lines starting 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 docstring.

    How to run a written program

    You must also run the written program on the command line. To do this, you need to write the name of the interpreter and, separated by a space, the name of the file with the written program. When starting the program, you must specify the full path to the file. This is not always easy, as the path can be very long, so sometimes it is easier to change the current directory on the command line and start the interpreter there. To do this, go 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, separated by a space, the name of the file that is in it.

    Language syntax

    The basics of programming using Python as an example are not very different from other languages, but variables have a slightly different meaning. Python has no required characters to complete statements. Any blocks are indented, so you must back out to run the block and remove it. For multi-line comments, you must use multi-line lines. Values ​​are assigned using the “=” sign, and equality testing is performed with two of them “==”. You can increase or decrease values ​​using the = or - = operators with the sum on the right. This can work with strings and other data types. You can also use multiple variables on one line.

    Data types in Python

    Now let's look at data types. Python is based on data structures - dict, tuples, and lists. Kits can be found in the Kits Library, which are available in all versions of Python. Lists are like one-dimensional arrays, although you can have lists of other lists as well. 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 beginning, and -1 is the last element. Variables can also point to functions.

    Strings in Python

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

    Functions in Python

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

    You have just started 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.

    Python Programming

    Part 1. Language features and syntax basics

    Content Series:

    Should you learn Python?

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

    Many programmers believe that it is necessary to learn only "classic" programming languages ​​such as Java or C ++, as other languages ​​still cannot provide the same capabilities. Recently, however, the conviction has arisen that it is desirable for a programmer to know more than one language, as this broadens his horizons, allowing him to more creatively solve tasks and increase his competitiveness in the labor market.

    Learning to perfect two languages ​​such as Java and C ++ is difficult and time-consuming; in addition, many aspects of these languages ​​contradict each other. At the same time, Python is ideal for the role of a second language, since it is immediately assimilated thanks to the already existing knowledge in OOP, and the fact that its capabilities do not conflict, but supplement the experience gained when working with another programming language.

    If a programmer is just starting his way in the field of software development, then Python will be the ideal "introductory" programming language. Due to its brevity, it will allow you to quickly master the syntax of the language, and the absence of "inheritance" in the form of axioms that have been formed over the years will help you quickly master OOP. Because of these factors, the Python learning curve will be quite short, and the programmer will be able to move from case studies to commercial projects.

    Therefore, whether the reader of this article is an experienced programmer or a newbie in the field of software development, the answer to the question, which is also the title of this section, should be a convincing "yes".

    This series of articles is designed to help you successfully overcome the learning curve by providing information consistently from the most basic principles of the language to its advanced capabilities in terms of integration with other technologies. The first article will cover the basic features and syntax of Python. In the future, we will look at more complex aspects of working with this popular language, in particular, object-oriented programming in Python.

    Python architecture

    Any language, no matter for programming or communication, consists of at least two parts - vocabulary and syntax. The Python language is organized in the same way, providing a syntax for forming expressions that make up executable programs, and a dictionary - a set of functionality in the form of a standard library and plug-ins.

    As mentioned, Python's syntax is quite concise, especially when compared to Java or C ++. On the one hand, this is good, because the simpler the syntax, the easier it is to learn and the fewer mistakes you can make while using it. However, such languages ​​have a drawback - with their help you can convey the simplest information and you cannot express complex structures.

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

    Also, Python is a general-purpose language, so it can be used in almost any area of ​​software development (standalone, client-server, Web-applications) and in any subject area. In addition, Python integrates seamlessly with existing components, allowing Python to be embedded into existing applications.

    Another component of Python's success is its plugins, both standard and specific. Python standard plugins are well-designed and proven functionality for solving the problems that arise in every software development project, processing strings and texts, interacting with the operating system, supporting web applications. These modules are also written in Python, so they have its most important property - cross-platform, which allows you to painlessly and quickly transfer projects from one operating system to another.

    If the required functionality is not in the standard Python library, you can create your own plug-in module for later reuse. It is worth noting here that Python plugins can be created not only in Python itself, but also using other programming languages. In this case, it becomes possible to more efficiently implement resource-intensive tasks, for example, complex scientific computing, but the advantage of cross-platform is lost if the plug-in language is not itself cross-platform, like Python.

    Python Runtime

    As you know, all cross-platform programming languages ​​are built on the same model: they are truly portable source code and a runtime environment, which is not portable and is platform-specific. This runtime usually includes an interpreter that executes the source code and the various utilities needed to maintain the application — a debugger, reverse assembler, and so on.

    The Java runtime also includes a compiler because the source code needs to be compiled into bytecode for the Java virtual machine. The Python runtime includes only an interpreter, which is also a compiler, but compiles the Python source code directly into the machine code of the target platform.

    There are currently three known runtime implementations for Python: CPython, Jython, and Python.NET. As the name suggests, the first framework is implemented in C, the second in Java, and the last in the .NET platform.

    The CPython runtime is usually just called Python, and when people talk about Python, this is the implementation that is most often referred to. This implementation consists of an interpreter and plug-ins written in C and can be used on any platform for which a standard C compiler is available. In addition, there are already compiled versions of the runtime for various operating systems, including various versions of Windows OC and various distributions. Linux. In this and subsequent articles, CPython will be considered, unless otherwise specified separately.

    The Jython runtime is a Python implementation for working with the Java Virtual Machine (JVM). Any JVM version is supported, starting from version 1.2.2 (current Java version is 1.6). Jython requires an installed Java machine (Java runtime) and some knowledge of the Java programming language. It is not necessary to be able to write source code in Java, but you will have to deal with JAR files and Java applets, as well as documentation in the JavaDOC format.

    Which version of the environment to choose depends solely on the preferences of the programmer; in general, it is recommended to keep both CPython and Jython on the computer, since they do not conflict with each other, but complement each other. CPython is faster because there is no middleware JVM; in addition, updated versions of Python are first released as the CPython environment. However, Jython can use any Java class as an extension and run on any platform for which a JVM implementation exists.

    Both runtime environments are released under a license compatible with the well-known GPL license, so they can be used to develop both commercial and free or free software. Most Python plugins are also GPL licensed and can be freely used in any project, but there are commercial extensions or extensions with stricter licenses. Therefore, when using Python in a commercial project, you need to be aware of the restrictions on plug-in licenses.

    Getting started with Python

    Before you start using Python, you need to install its runtime environment - in this article, it is CPython and, accordingly, the python interpreter. There are various installation methods: advanced users can compile Python themselves from its public source code, pre-built binaries for a specific operating system can also be downloaded from www.python.org, and finally, many Linux distributions come with a pre-installed Python interpreter. This article uses the Windows version of Python 2.x, but the examples provided can be run on any version of Python.

    After the installer has deployed the Python binaries to the specified directory, you need to check the values ​​of the following system variables:

    • PATH. This variable must contain the path to the directory where Python is installed so that the operating system can find it.
    • PYTHONHOME. This variable should only contain the path to the directory where Python is installed. This directory should also contain a lib subdirectory that will search for standard Python modules.
    • PYTHONPATH. Variable with a list of directories containing extension modules that will connect to Python (list items must be separated by a system separator).
    • PYTHONSTARTUP. An optional variable that specifies the path to the Python script to be executed each time an interactive Python interpreter session starts.

    The command line for working with the interpreter has the following structure.

    PYTHONHOME \ python (options) [-с command | script file | -] (arguments)

    Python interactive mode

    If you start the interpreter without specifying a command or script file, it will start in interactive mode. In this mode, a special Python shell is launched, into which individual commands or expressions can be entered, and their value will be immediately evaluated. This is very convenient when learning Python, since you can immediately check the correctness of one or another construction.

    The value of the evaluated expression is stored in a special variable named Single Underscore (_) so that it can be used in subsequent expressions. You can end an interactive session by pressing Ctrl – Z on Windows or Ctrl – D on Linux.

    Options are optional string values ​​that can change the behavior of the interpreter during a session; their significance will be discussed in this and subsequent articles. Options are followed by either a single command that the interpreter must execute, or the path to the file that contains the script to execute. It is worth noting that a command can consist of several expressions, separated by semicolons, and must be enclosed in quotation marks so that the operating system can correctly pass it to the interpreter. Arguments - those parameters that are passed for further processing to the executable script; they are passed to the program as strings and separated by spaces.

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

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

    The –v option displays the version of the Python implementation in use and exits, while the second command prints the system time to the screen.

    You can write Python scripts in any text editor, since they are ordinary text files, but there are also special development environments designed to work with Python.

    Python syntax basics

    Python source scripts are composed of so-called logical lines, each of which in turn consists of physical lines... The # symbol is used to indicate comments. The interpreter ignores comments and empty lines.

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

    Physical lines are separated by the end-of-line character itself, but if the expression is too long for one line, then the two physical lines can be merged into one logical line. To do this, you must enter a backslash character (\) at the end of the first line, and then the next line will be interpreted by the interpreter as a continuation of the first, but you cannot have other characters on the first line after the \ character, for example, a comment with #. Only indentation is used to highlight blocks of code. Equally indented logical lines form a block, and the block ends when a smaller indented logical line appears. This is why the first line in a Python script should not be indented. Learning these simple rules will help you avoid most of the mistakes associated with learning a new language.

    There are no other radical differences from other programming languages ​​in the Python syntax. There is a standard set of operators and keywords, most of which are already familiar to programmers, and Python-specific ones will be covered in this and subsequent articles. The standard rules for specifying identifiers of variables, methods and classes are also used - the name must begin with an underscore or a Latin character of any case and cannot contain the @, $,% symbols. Also, only one underscore character cannot be used as an identifier (see footnote about interactive mode).

    Data types used in Python

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

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

    Functionality for working with datasets

    Python defines three types of collections for storing datasets:

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

    A tuple is an immutable, ordered sequence of data. It can contain elements of various types, such as other tuples. A tuple is defined in parentheses, and its elements are separated by commas. The special built-in function tuple () allows you to create tuples from a given sequence of data.

    A list is a mutable, ordered sequence of items. List items are also separated by commas, but are specified in square brackets. The list () function is proposed to create lists.

    A dictionary is a hash table that stores an element along with its key identifier. Subsequent access to the elements is also performed by key, so the storage unit in the dictionary is an object-key pair and its associated value object. A dictionary is a mutable, but not ordered, collection, so the order of elements in a dictionary can change over time. A dictionary is specified in curly braces, the key is separated from the value by a colon, and the key / value pairs themselves are separated by commas. The dict () function is available to create dictionaries.

    Listing 1 shows examples of the various collections available in Python.

    Listing 1. Collection types available in Python
    ('w', 'o', 'r', 'l', 'd') # a tuple of five elements (2.62,) # a tuple of one element [“test”, "me"] # a list of two elements # empty list (5: 'a', 6: 'b', 7: 'c') # 3-element dictionary with keys of type int

    Defining Functions in Python

    Although Python supports OOP, many of its features are implemented as separate functions; in addition, extension modules are most often made in the form of a library of functions. Functions are also used in classes, where they are traditionally called methods.

    The syntax for defining functions in Python is extremely simple; taking into account the above requirements:

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

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

    FUNCTION_NAME (parameters)

    There are only a few Python-specific points to consider. As in Java, primitive values ​​are passed by value (a copy of the parameter is passed to the function and it cannot change the value set before the function was called), and complex object types are passed by reference (a reference is passed to the function and it may well change the object).

    Parameters can be passed either simply in the order of enumeration or by name, in this case it is not necessary to indicate when calling those parameters for which there are default values, but to pass only mandatory ones or change the order of parameters when calling the function:

    # function that performs integer division using the statement // def foo (delimoe, delitel): return delimoe // delitel print divide (50,5) # result of work: 10 print divide (delitel = 5, delimoe = 50) # result work: 10

    A Python function must return a value — either explicitly with a return statement followed by a return value, or, in the absence of a return statement, the constant None is returned when the end of the function is reached. As you can see from the examples of function declarations, in Python there is no need to indicate whether something is returned from a function or not, however, if the function has one return statement that returns a value, then other return statements in this function must return values, and if such a value no, then you must explicitly write return None.

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

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

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

    Is it worth learning the Python programming language? 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 in size. 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 ​​both gain in popularity and lose it. Productivity is a major challenge in programming, so from time to time new languages ​​are created that increase productivity for at least some kinds of work.

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

    The 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 that 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. His weakness is that you need to understand his style in order 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 usually 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's good for data and database management as well as networking programming. It is a thoughtful language with a huge amount of resources available.

    3. Serious scientific data libraries

    • Python has significant scientific libraries with a huge amount of data to use.
    • The backbone of these scientific libraries is the SciPy Ecosystem, which even hosts its own conferences.
    • Pandas and Matplotlib are both part of SciPy. They provide superior data on a wide variety of topics such as machine learning, text mining, 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 which 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 family of languages.

    Magnus Lyczka, software developer 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. And if these startups started working in assembly language, they would most likely have run out of funding long before their the quick but hard-to-read code would be complete.

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

    Top related articles