How to set up smartphones and PCs. Informational portal
  • home
  • Advice
  • Python programming lessons from scratch. The Python programming language is dying

Python programming lessons from scratch. The Python programming language is dying

(Translation)

The Poromenos "Stuff site has published an article in which, in a concise manner, they talk about the basics of the Python language. I offer you a translation of this article. The translation is not literal. I have tried to explain in more detail some points that may not be clear.

If you are looking to learn the Python language, but cannot find a suitable guide, then this article will be very useful to you! In a short time, you will be able to familiarize yourself with the basics of the Python language. Although this article often relies on the fact that you already have programming experience, I hope that even beginners will find this material useful. Read each paragraph carefully. Due to the compactness of the material, some topics are considered superficially, but contain all the necessary metrics.

Basic properties

Python does not require explicit declaration of variables, it is case-sensitive (var is not equivalent to Var or VAR are three different variables) object-oriented language.

Syntax

First, it's worth noting an interesting feature of Python. It does not contain operator brackets (begin..end in pascal or (..) in C), instead blocks are indented: by spaces or tabs, and entering a block of statements is done with a colon. Single-line comments begin with the pound sign "#", multi-line comments begin and end with three double quotes "" "" ".

The "=" sign is used to assign a value to a variable, and "==" is used for comparison. To increase the value of a variable, or add to a line, use the "+ =" operator, and to decrease - "- =". All of these operations can interact with most types, including strings. for instance

>>> myvar = 3

>>> myvar + = 2

>>> myvar - = 1

"" "This is a multi-line comment

Lines enclosed in three double quotes are ignored "" "

>>> mystring = "Hello"

>>> mystring + = "world."

>>> print mystring

Hello world.

# The next line changes

Variable values ​​in places. (Just one line!)

>>> myvar, mystring = mystring, myvar

Data structures

Python contains data structures such as lists, tuples, and dictionaries). Lists are like one-dimensional arrays (but you can use Including lists - a multidimensional array), tuples are immutable lists, dictionaries are also lists, but indices can be of any type, not just numeric ones. "Arrays" in Python can contain data of any type, that is, one array can contain numeric, string and other data types. Arrays start at index 0, and the last element can be obtained at index -1. You can assign functions to variables and use them accordingly.

>>> sample =, ("a", "tuple")] # The list consists of an integer, another list and a tuple

>>> mylist = ["List item 1", 2, 3.14] # This list contains a string, an integer and a fraction

>>> mylist = "List item 1 again" # Change the first (zero) element of the list mylist

>>> mylist [-1] = 3.14 # Change the last element of the sheet

>>> mydict = ("Key 1": "Value 1", 2: 3, "pi": 3.14) # Create a dictionary, with numeric and integer indices

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

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

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

>>> print myfunction (mylist)

You can use part of an array by specifying the first and last index separated by colon ":". In this case, you will receive a part of the array, from the first index to the second, not inclusive. If the first element is not specified, then the counting starts from the beginning of the array, and if the last is not specified, then the array is read up to the last element. Negative values ​​define the end position of the element. For instance:

>>> mylist = ["List item 1", 2, 3.14]

>>> print mylist [:] # All array elements are read

["List item 1", 2, 3.1400000000000001]

>>> print mylist # The zero and the first array element are read.

["List item 1", 2]

>>> print mylist [-3: -1] # Read items from zero (-3) to second (-1) (not inclusive)

["List item 1", 2]

>>> print mylist # Items are read from first to last

Strings

Strings in Python separated by double quotes "" "or single" ""... Single quotes can be present inside double quotes or vice versa. For example, the line "He said hello!" will be displayed as "He said hello!" If you need to use a string of several lines, then this line must begin and end with three double quotes "" "" ". You can substitute elements from a tuple or a dictionary into the string template. The percent sign"% "between the string and the tuple, replaces characters in the string "% S" on an element of a tuple. Dictionaries allow you to insert into a string an element at a given index.

>>> print "Name:% s \ nNumber:% s \ nString:% s"% (myclass.name, 3, 3 * "-")

Name: Poromenos

Number: 3

String: ---

strString = "" "This text is located

on multiple lines "" "

>>> print "This% (verb) s a% (noun) s." % ("noun": "test", "verb": "is")

This is a test.

Operators

The while, if, for statements make up the move statements. There is no analogue of the select statement, so you have to get around if. Comparison takes place in the for statement variable and list... To get a list of digits up to a number - use the function range ( ). Here is an example of using the operators

rangelist = range (10) # Get a list of ten digits (0 to 9)

>>> print rangelist

for number in rangelist: # While the variable number (which is incremented each time) enters the list ...

# Check if the variable is included

# numbers to a tuple of numbers (3, 4, 7, 9)

If number in (3, 4, 7, 9): # If the variable number is in the tuple (3, 4, 7, 9) ...

# The "break" operation provides

# exit the loop at any time

Break

Else:

# "Continue" scrolls

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

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

Continue

else:

# "Else" is optional. Condition is met

# unless the loop was interrupted with "break".

Pass # Do nothing

if rangelist == 2:

Print "The second item (lists are 0-based) is 2"

elif rangelist == 3:

Print "The second item (lists are 0-based) is 3"

else:

Print "Dunno"

while rangelist == 1:

Pass

Functions

To declare a function, use keyword "def"... Function arguments are specified in parentheses after the function name. You can supply optional arguments, giving them a default value. Functions can return tuples, in which case return values ​​must be separated by commas. The lambda keyword is used to declare elementary functions.

# arg2 and arg3 are optional arguments, take the default value,

# unless you give them a different value when calling the function.

def myfunction (arg1, arg2 = 100, arg3 = "test"):

Return arg3, arg2, arg1

# The function is called with the value of the first argument - "Argument 1", the second - by default, and the third - "Named argument".

>>> ret1, ret2, ret3 = myfunction ("Argument 1", arg3 = "Named argument")

# ret1, ret2 and ret3 take the values ​​"Named argument", 100, "Argument 1" respectively

>>> print ret1, ret2, ret3

Named argument 100 Argument 1

# The following is equivalent to def f (x): return x + 1

functionvar = lambda x: x + 1

>>> print functionvar (1)

Classes

The Python language is limited in multiple inheritance in classes. Internal variables and internal class methods begin with two underscores "__" (for example, "__myprivatevar"). We can also assign the value to a class variable externally. Example:

class Myclass:

Common = 10

Def __init __ (self):

Self.myvariable = 3

Def myfunction (self, arg1, arg2):

Return self.myvariable

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

>>> classinstance = Myclass () # We have initialized the class and myvariable is set to 3 as declared in the initialization method

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

# The common variable is declared in all classes

>>> classinstance2 = Myclass ()

>>> classinstance.common

>>> classinstance2.common

# Therefore, if we change its value in the class Myclass will change

# and its values ​​in objects initialized by Myclass

>>> Myclass.common = 30

>>> classinstance.common

>>> classinstance2.common

# And here we are not modifying the class variable. Instead of this

# we declare it in the object and assign a new value to it

>>> classinstance.common = 10

>>> classinstance.common

>>> classinstance2.common

>>> Myclass.common = 50

# Now changing the class variable will not touch

# variables of objects of this class

>>> classinstance.common

>>> classinstance2.common

# The following class inherits from the Myclass class

# inheriting its properties and methods, besides the class can

# inherit from several classes, in this case write

# like this: class Otherclass (Myclass1, Myclass2, MyclassN)

class Otherclass (Myclass):

Def __init __ (self, arg1):

Self.myvariable = 3

Print arg1

>>> classinstance = Otherclass ("hello")

hello

>>> classinstance.myfunction (1, 2)

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

# declare such a variable for an object. And

# this variable will be a member of classinstance only.

>>> classinstance.test = 10

>>> classinstance.test

Exceptions

Python exceptions have a try -except structure:

def somefunction ():

Try:

# Division by zero raises an error

10 / 0

Except ZeroDivisionError:

# But the program does not "Perform an illegal operation"

# A handles the exception block corresponding to the "ZeroDivisionError"

Print "Oops, invalid."

>>> fnexcept ()

Oops, invalid.

Import

External libraries can be connected using the "import" procedure, where is the name of the library being connected. You can also use the "from import" command so that you can use the function from the library:

import random # Import the "random" library

from time import clock # And at the same time the "clock" function from the "time" library

randomint = random.randint (1, 100)

>>> print randomint

Working with the file system

Python has many built-in libraries. In this example, we will try to save the list structure in a binary file, read it, and save the string to a text file. To transform the data structure, we will use the "pickle" standard library:

import pickle

mylist = ["This", "is", 4, 13327]

# Open file C: \ binary.dat for writing. The "r" symbol

# prevents the replacement of special characters (such as \ n, \ t, \ b, etc.).

myfile = file (r "C: \ binary.dat", "w")

pickle.dump (mylist, myfile)

myfile.close ()

myfile = file (r "C: \ text.txt", "w")

myfile.write ("This is a sample string")

myfile.close ()

myfile = file (r "C: \ text.txt")

>>> print myfile.read ()

"This is a sample string"

myfile.close ()

# Open the file for reading

myfile = file (r "C: \ binary.dat")

loadedlist = pickle.load (myfile)

myfile.close ()

>>> print loadedlist

["This", "is", 4, 13327]

Peculiarities

  • Conditions can be combined. 1 < a < 3 выполняется тогда, когда а больше 1, но меньше 3.
  • Use the "del" operation to clear variables or array elements.
  • Python offers great opportunities for work with lists... You can use operators to declare a list structure. The for statement allows you to specify the elements of a list in a specific sequence, and if - allows you to select items by condition.

>>> lst1 =

>>> lst2 =

>>> print

>>> print

# The "any" operator returns true if at least

# would one of the conditions included in it are met.

>>> any (i% 3 for i in)

True

# The following procedure calculates the number of

# matching items in the list

>>> sum (1 for i in if i == 3)

>>> del lst1

>>> print lst1

>>> del lst1

  • Global Variables are declared outside of functions and can be read without any declarations. But if you need to change the value of a global variable from a function, then you need to declare it at the beginning of the function with the keyword "global", if you do not, then Python will declare a variable available only for this function.

number = 5

def myfunc ():

# Prints 5

Print number

def anotherfunc ():

# This throws an exception because the global variable

# was not called from a function. Python in this case creates

# variable of the same name inside this function and available

# for operators of this function only.

Print number

Number = 3

def yetanotherfunc ():

Global number

# And only from this function, the value of the variable is changed.

Number = 3

Epilogue

Of course, this article does not cover all the features of Python. I hope this article will help you if you want to continue learning this programming language.

Benefits of Python

  • The execution speed of programs written in Python is very high. This is due to the fact that the main Python libraries
    are written in C ++ and take less time to complete tasks than other high-level languages.
  • Due to this, you can write your own modules for Python in C or C ++
  • In the standard Python libraries you can find tools for working with email, protocols
    Internet, FTP, HTTP, databases, etc.
  • Python scripts run on most modern operating systems. This portability allows Python to be used in a wide variety of areas.
  • Python is suitable for any programming solution, be it office programs, web applications, GUI applications, etc.
  • Thousands of enthusiasts from all over the world have worked on Python development. The support of modern technologies in the standard libraries can be attributed to the fact that Python was open to everyone.

Once upon a time, on a closed forum, I tried to teach Python. In general, the case has died out there. I felt sorry for the written lessons, and I decided to post them to the general public. So far, the very first, the simplest. The next is more interesting, but maybe it will not be interesting. In general, this post will be a trial balloon, if you like it, I will post it further.

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

Just in case, a little boring "evangelism". If you are tired of it, you can skip a few paragraphs.
Python (reads "Python" not "Python") is a scripting language developed by Guido van Rossum as a simple language that is easy for a beginner to learn.
Nowadays, Python is a widely spoken language that is used in many areas:
- Development of application software (for example, linux utilities yum, pirut, system-config- *, Gajim IM client and many others)
- Development of web applications (the most powerful Application server Zope and the CMS Plone developed on its basis, on the basis of which, for example, the CIA website works, and a lot of frameworks for the rapid development of applications Plones, Django, TurboGears and many others)
- Use as an embedded scripting language in many games, and not only (in the OpenOffice.org office suite, Blender 3d editor, Postgre DBMS)
- Use in scientific calculations (with the SciPy and numPy packages for calculations and PyPlot for drawing Python graphs becomes almost comparable to packages like MatLab)

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

1. The interpreter itself, you can take it here (http://python.org/download/).
2. Development environment. For a start, it is optional, and the IDLE included in the distribution will suit a beginner, but for serious projects you need something more serious.
For Windows I use the wonderful lightweight PyScripter (http://tinyurl.com/5jc63t), for Linux I use the Komodo IDE.

Although for the first lesson, just an interactive shell of Python itself will be enough.

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

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

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

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

Finally, you can use one of the many convenient Python IDEs that provide both debugging and syntax highlighting and many other "conveniences".

A bit of theory.

For starters, Python is a strongly dynamically typed language. What does this mean?

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

>>> a = b = 1 >>> a, b (1, 1) >>> b = 2 >>> a, b (1, 2) >>> a, b = b, a >>> a , b (2, 1)

Thus, we see that the assignment is carried out using the = sign. You can assign a value to several variables at once. When instructing the interpreter to name a variable interactively, it prints its value.

The next thing to know is how the basic algorithmic units are built - branches and loops. First, a little background is needed. There is no special code block delimiter in Python; indents play their role. That is, what is written with the same indentation is one command block. At first it may seem strange, but after a little getting used to, you realize that this "forced" measure allows you to get very readable code.
So the conditions.

The condition is set using an if statement that ends with ":". Alternative conditions that will be fulfilled if the first check "failed" are specified by the elif operator. Finally, else sets the branch that will be executed if none of the conditions match.
Note that after typing if, the interpreter uses the "..." prompt to indicate that it is waiting for input to continue. To inform him that we are finished, you must enter an empty line.

(The example with branches for some reason tears the markup on Habré, despite the dances with the pre and code tags. Sorry for the inconvenience, I threw it here pastebin.com/f66af97ba, if someone tells me what is wrong, I will be very grateful)

Cycles.

The simplest case for a loop is a while loop. As a parameter, it accepts a condition and is executed as long as it is true.
Here's a small example.

>>> x = 0 >>> while x<=10: ... print x ... x += 1 ... 0 1 2 ........... 10

Note that since both print x and x + = 1 are written with the same indentation, they are considered the body of the loop (remember what I said about blocks? ;-)).

The second type of loop in Python is the for loop. It is similar to the foreach loop in other languages. Its syntax is conventionally as follows.

For variable in list:
commands

The variable will be assigned in turn all the values ​​from the list (in fact, there can be not only a list, but also any other iterator, but we will not bother with this for now).

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

>>> x = "Hello, Python!" >>> for char in x: ... print char ... H e l ...........!

This way we can expand the string character by character.
What if we want a loop that repeats a certain number of times? Quite simply, the range function comes to the rescue.

At the input, it accepts from one to three parameters, at the output it returns a list of numbers, through which we can "walk" with the for statement.

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

>>> range (10) >>> range (2, 12) >>> range (2, 12, 3) >>> range (12, 2, -2)

And a small example with a loop.

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

Input Output

The last thing to know before you start using Python fully is how I / O is performed in it.

For output, use the print command, which prints out all of its arguments in a human readable form.

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

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

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

That's it for the first lesson.

Homework.

1. Make a program for calculating the hypotenuse of a right-angled triangle. The length of the legs is requested from the user.
2. Make a program for finding the roots of a quadratic equation in general form. The odds are requested from the user.
3. Make a program for outputting the multiplication table by the number M. The table is compiled from M * a to M * b, where M, a, b are requested from the user. The output should be carried out in a column, one example per line in the following form (for example):
5 x 4 = 20
5 x 5 = 25
Etc.

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:

Introduction


In connection with the currently observed rapid development of personal computing technology, there is a gradual change in the requirements for programming languages. Interpreted languages ​​are beginning to play an increasing role, as the increasing power of personal computers begins to provide sufficient speed for the execution of interpreted programs. And the only significant advantage of compiled programming languages ​​is the high-speed code they create. When the speed of program execution is not a critical value, the most correct choice is an interpreted language, as it is a simpler and more flexible programming tool.

In this regard, it is of some interest to consider a relatively new programming language Python (Python), which was created by its author Guido van Rossum in the early 90s.

General information about Python. Advantages and disadvantages


Python is an interpreted, natively object-oriented programming language. It is extremely simple and contains a small number of keywords, at the same time it is very flexible and expressive. It is a language of a higher level than Pascal, C ++ and, of course, C, which is achieved mainly due to the built-in high-level data structures (lists, dictionaries, tuples).

The virtues of language.
The undoubted advantage is that the Python interpreter is implemented on almost all platforms and operating systems. The first such language was C, but its data types on different machines could take up different amounts of memory and this served as some obstacle when writing a truly portable program. Python doesn't have this disadvantage.

The next important feature is the extensibility of the language, great importance is attached to this and, as the author himself writes, the language was conceived precisely as extensible. This means that there is an opportunity for improvement of the language by all interested programmers. The interpreter is written in C and the source code is available for any manipulation. If necessary, you can insert it into your program and use it as a built-in shell. Or, by writing your Python add-ons in C and compiling the program, you can get an "extended" interpreter with new features.

The next advantage is the presence of a large number of plug-in modules that provide various additional features. Such modules are written in C and in Python itself and can be developed by any reasonably qualified programmer. The following modules can be cited as examples:

  • Numerical Python - Advanced math capabilities such as integer vector and matrix manipulation.
  • Tkinter - building applications using a graphical user interface (GUI) based on the widely used Tk interface on X-Windows;
  • OpenGL - Uses Silicon Graphics Inc.'s extensive 2D and 3D graphics modeling library, Open Graphics Library. This standard is supported, among other things, in such common operating systems as Microsoft Windows 95 OSR 2, 98 and Windows NT 4.0.
Disadvantages of the language.
The only drawback noted by the author is the relatively low execution speed of the Python program, which is due to its interpretability. However, in our opinion, this is more than compensated by the advantages of the language when writing programs that are not very critical to the speed of execution.

Features overview


1. Python, unlike many languages ​​(Pascal, C ++, Java, etc.), does not require variable declarations. They are created in the place of their initialization, i.e. the first time you assign a value to a variable. This means that the type of the variable is determined by the type of the assigned value. Python resembles Basic in this respect.
The type of the variable is not immutable. Any assignment for it is correct and this only leads to the fact that the type of the variable becomes the type of the new assigned value.

2. In languages ​​such as Pascal, C, C ++, the organization of lists presented some difficulties. To implement them, one had to study well the principles of working with pointers and dynamic memory. And even having good qualifications, a programmer, each time re-implementing the mechanisms for creating, working and destroying lists, could easily make subtle mistakes. In view of this, some tools have been created for working with lists. For example, Delphi Pascal has a TList class that implements lists; for C ++, the STL (Standard Template Library) library has been developed, containing such structures as vectors, lists, sets, dictionaries, stacks and queues. However, such facilities are not available in all languages ​​and their implementations.

One of the distinguishing features of Python is the presence of such structures built into the language itself as tuples(tuple), the lists(list) and dictionaries(dictionary) sometimes called maps(map). Let's consider them in more detail.

  1. Tuple ... It is somewhat reminiscent of an array: it consists of elements and has a strictly defined length. Elements can be any value - simple constants or objects. Unlike an array, Tuple elements are not necessarily uniform. And what distinguishes a tuple from a list is that a tuple cannot be changed, i.e. we cannot assign something new to the i-th tuple element and we cannot add new elements. Thus, Tuple can be called a constant list. Syntactically, tuple is specified by listing all elements separated by commas, and all of this is enclosed in parentheses:

  2. (1, 2, 5, 8)
    (3.14, 'string', -4)
    All elements are indexed from scratch. To get the i-th element, you must specify the name of the tuple then the index i in square brackets. Example:
    t = (0, 1, 2, 3, 4)
    print t, t [-1], t [-3]
    Result: 0 4 2
    Thus, the Tuple could be called a constant vector if its elements were always uniform.
  3. List ... A good example of a list is a Turbo Pascal string. The elements of a string are single characters, its length is not fixed, it is possible to delete elements or, on the contrary, insert them anywhere in the string. The elements of the list can be arbitrary objects, not necessarily of the same type. To create a list, it is enough to list its elements separated by commas, enclosing all this in square brackets:


  4. [‘String’, (0,1,8),]
    Unlike Tuple, lists can be modified as desired. The elements are accessed in the same way as in the tuples. Example:
    l =]
    print l, l, l [-2], l [-1]
    Result: 1 s (2.8) 0
  5. Dictionary ... It resembles a record type in Pascal or a structure type in C. However, instead of the "record field" - "value" schema, it uses "key" - "value". A dictionary is a set of "key" - "value" pairs. Here "key" is a constant of any type (but strings are mostly used), it serves for naming (indexing) some value corresponding to it (which can be changed).

  6. A dictionary is created by listing its elements ("key" - "value" pairs, separated by a colon), separated by commas, and enclosing them all in curly braces. To gain access to a certain value, it is necessary to write the corresponding key in square brackets after the name of the dictionary. Example:
    d = ("a": 1, "b": 3, 5: 3.14, "name": "John")
    d ["b"] = d
    print d ["a"], d ["b"], d, d ["name"]
    Result: 1 3.14 3.14 John
    To add a new pair "key" - "value", it is enough to assign the corresponding value to the element with the new key:
    d ["new"] = "new value"
    print d
    Result: ("a": 1, "b": 3, 5: 3.14, "name": "John", "new": "new value")

3. Python unlike Pascal, C, C ++ does not support working with pointers, dynamic memory and address arithmetic. In this it is similar to Java. As you know, pointers are a source of subtle errors and working with them is more related to programming at a low level. For greater reliability and simplicity, they have not been included in Python.

4. One of the peculiarities of Python is how one variable is assigned to another, ie. when on both sides of the operator " = "there are variables.

Following Timothy Budd (), we will call semantics of pointers the case when the assignment only leads to the assignment of a reference (pointer), i.e. the new variable becomes just a different name, denoting the same memory location as the old variable. In this case, a change in the value designated by the new variable will lead to a change in the value of the old one, since they actually mean the same thing.

When the assignment leads to the creation of a new object (here the object is in the sense of a piece of memory for storing a value of some type) and copying the contents of the assigned variable into it, we will call this case copy semantics... Thus, if the copying semantics are valid when copying, then the variables on both sides of the "=" sign will mean two independent objects with the same content. And here the subsequent change in one variable will not affect the other in any way.

Assignment in Python works like this: if assignable an object is an instance of such types as numbers or strings, then the copying semantics applies, but if on the right side there is an instance of a class, a list, a dictionary or a tuple, then the semantics of pointers apply. Example:
a = 2; b = a; b = 3
print "copy semantics: a =", a, "b =", b
a =; b = a; b = 3
print "pointer semantics: a =", a, "b =", b
Result:
copy semantics: a = 2 b = 3
pointer semantics: a = b =

For those of you who want to know what this is, I'll take a different look at assignment in Python. If in such languages ​​as Basic, Pascal, C / C ++ we dealt with variables - "capacities", and the constants stored in them (numeric, symbolic, string - not the point), and the assignment operation meant "putting" the constant into the variable being assigned , then in Python we already have to work with variable "names" and objects named by them. (Do you notice some analogy with the Prolog language?) What is an object in Python? This is everything that can be given a name: numbers, strings, lists, dictionaries, instances of classes (which in Object Pascal are called objects), the classes themselves (!), Functions, modules, etc. So, when assigning a variable to some object, the variable becomes its "name", and the object can have any number of such "names" and they all do not depend on each other in any way.

Now, objects are divided into modifiable (mutable) and immutable. Mutable - those that can change their "internal content", for example, lists, dictionaries, class instances. And immutable ones - such as numbers, tuples, strings (yes, strings too; you can assign a variable to a new string derived from the old one, but you cannot modify the old string itself).

So if we write a =; b = a; b = 3 Python interprets it like this:

  • give object "a list " name a ;
  • give this object another name - b ;
  • modify the zero element of the object.

  • So we got the "pseudo" semantics of pointers.

    And the last thing to say about this: although there is no possibility of changing the structure of the tuple, but the mutable components contained in it are still available for modification:

    T = (1, 2,, "string") t = 6 # this is not allowed del t # also an error t = 0 # allowed, now the third component is a list t = "S" # error: strings are not mutable

    5. The way operators are grouped in Python is quite original. In Pascal, operator brackets are used for this. begin-end, in C, C ++, Java - curly braces (), in Basic, closing endings of language constructs (NEXT, WEND, END IF, END SUB) are used.
    In Python, everything is much simpler: the selection of a block of statements is carried out by shifting the selected group by one or more spaces or tabulation characters to the right relative to the title of the structure to which this block will refer. For instance:

    if x> 0: print ‘x> 0’ x = x - 8 else: print ‘x<= 0 ’ x = 0 Thus, the good writing style of programs that teachers of Pascal, C ++, Java, etc. call for, is acquired here from the very beginning, because it simply will not work in another way.

    Description of the language. Control constructs



    Exception handling


    try:
    <оператор1>
    [except[<исключение> [, <переменная>] ]:
    <оператор2>]
    [else <оператор3>]
    Performed<оператор1>if an exception occurs<исключение>, then it is executed<оператор2>... If<исключение>matters, then it is assigned<переменной>.
    In case of successful completion<оператора1>, performed<оператор3>.
    try:
    <оператор1>
    finally:
    <оператор2>
    Performed<оператор1>... If no exceptions are thrown, then<оператор2>... Otherwise,<оператор2>and an exception is thrown immediately.
    raise <исключение> [<значение>] Initiates an exceptional situation<исключение>with parameter<значение>.

    Exceptions are just strings. Example:

    My_ex = ‘bad index’ try: if bad: raise my_ex, bad except my_ex, value: print ‘Error’, value

    Function declaration



    Declaring classes



    Class cMyClass: def __init __ (self, val): self.value = val # def printVal (self): print 'value =', self.value # # end cMyClass obj = cMyClass (3.14) obj.printVal () obj.value = "(! LANG: string now" obj.printVal () !} Result:
    value = 3.14
    value = string now

    Operators for all types of sequences (lists, tuples, strings)


    Operators for lists (list)


    s [i] = x The i-th element of s is replaced with x.
    s = t some of the elements s from i to j-1 are replaced with t (t can also be a list).
    del s removes the s part (as well as s =).
    s.append (x) adds the element x to the end of s.
    s.count (x) returns the number of elements s equal to x.
    s.index (x) returns the smallest i such that s [i] == x.
    s.insert (i, j) the part of s starting from the i-th element is shifted to the right, and s [i] is assigned to x.
    s.remove (x) same as del s [s.index (x)] - removes the first element of s equal to x.
    s.reverse () writes the string in reverse order
    s.sort () sorts the list in ascending order.

    Dictionary operators


    File objects


    Created by inline function open ()(see its description below). For instance: f = open (‘mydan.dat’, ‘r’).
    Methods:

    Other language elements and built-in functions


    = assignment.
    print [ < c1 > [, < c2 >]* [, ] ] outputs values< c1 >, < c2 >to standard output. Put a space between arguments. If there is no comma at the end of the list of arguments, then a newline is performed.
    abs (x) returns the absolute value of x.
    apply ( f , <аргументы>) calls function (or method) f with< аргументами >.
    chr (i) returns a single-character string with ASCII code i.
    cmp (x, y) returns negative, zero, or positive if x is respectively<, ==, или >than y.
    divmod (a, b) returns tuple (a / b, a% b), where a / b is a div b (integer part of division result), and% b is a mod b (remainder of division).
    eval (s)
    returns the object specified in s as a string. S can contain any structure of the language. S can also be a code object, for example: x = 1; incr_x = eval ("x + 1").
    float (x) returns a real value equal to the number x.
    hex (x) returns a string containing the hexadecimal representation of x.
    input (<строка>) deduces<строку>, reads and returns a value from standard input.
    int (x) returns the integer value of the number x.
    len (s) returns the length (number of elements) of the object.
    long (x) returns a long integer type value x.
    max (s), min (s) return the largest and smallest of the elements of the sequence s (that is, s is a string, list, or tuple).
    oct (x) returns a string containing the representation of the number x.
    open (<имя файла>, <режим>= ‘R’ ) returns a file object open for reading.<режим>= ‘W’ - opening for writing.
    ord (c) returns the ASCII code of the character (string of length 1) c.
    pow (x, y) returns the value of x to the power of y.
    range (<начало>, <конец>, <шаг>) returns a list of integers greater than or equal to<начало>and less than<конец>generated with a given<шагом>.
    raw_input ( [ <текст> ] ) deduces<текст>to standard output and reads a string from standard input.
    round (x, n = 0) returns real x rounded to the nth decimal place.
    str (<объект>) returns a string representation<объекта>.
    type (<объект>) returns the type of the object.
    For example: if type (x) == type (‘’): print ‘this is a string’
    xrange (<начало>, <конец>, <шаг>) similar to range, but only mimics the list without creating it. Used in a for loop.

    Special functions for working with lists


    filter (<функция>, <список>) returns a list of those elements<спиcка>for which<функция>takes on the value "true".
    map (<функция>, <список>) applies<функцию>to each element<списка>and returns a list of results.
    reduce ( f , <список>,
    [, <начальное значение> ] )
    returns the value obtained by "reduction"<списка>function f. This means that there is some internal variable p, which is initialized<начальным значением>, then, for each element<списка>, function f is called with two parameters: p and element<списка>... The result returned by f is assigned to p. After going through everything<списка>reduce returns p.
    Using this function, you can, for example, calculate the sum of the elements of a list: def func (red, el): return red + el sum = reduce (func,, 0) # now sum == 15
    lambda [<список параметров>] : <выражение> an "anonymous" function that does not have its own name and is written at the place of its call. Accepts the parameters specified in<списке параметров>, and returns the value<выражения>... Used for filter, reduce, map. For instance: >>> print filter (lambda x: x> 3,) >>> print map (lambda x: x * 2,) >>> p = reduce (lambda r, x: r * x,, 1) >>> print p 24

    Importing Modules



    Standard math module


    Variables: pi, e.
    Functions(similar to C language functions):

    acos (x) cosh (x) ldexp (x, y) sqrt (x)
    asin (x) exp (x) log (x) tan (x)
    atan (x) fabs (x) sinh (x) frexp (x)
    atan2 (x, y) floor (x) pow (x, y) modf (x)
    ceil (x) fmod (x, y) sin (x)
    cos (x) log10 (x) tanh (x)

    String module


    Functions:

    Conclusion


    Due to the simplicity and flexibility of the Python language, it can be recommended to users (mathematicians, physicists, economists, etc.) who are not programmers, but who use computing technology and programming in their work.
    Programs in Python are developed on average one and a half to two (and sometimes two to three) times faster than in compiled languages ​​(C, C ++, Pascal). Therefore, the language may be of no small interest to professional programmers who develop applications that are not critical to the speed of execution, as well as programs using complex data structures. In particular, Python has proven itself well in the development of programs for working with graphs and generating trees.

    Literature


    1. Budd T. Object-Oriented Programming. - SPb .: Peter, 1997.
    2. Guido van rossum... Python Tutorial. (www.python.org)
    3. Chris hoffman... A Python Quick Reference. (www.python.org)
    4. Guido van rossum... Python Library Reference. (www.python.org)
    5. Guido van rossum... Python Reference Manual. (www.python.org)
    6. Guido van Rossum... Python Programming Workshop. (http://sultan.da.ru)

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

    Sections:

    For beginners

    It is an excellent and internationally recognized introduction to the Python language. It quickly teaches you how to write efficient, high-quality code. Suitable for both novice programmers and those who already have experience in using other languages. In addition to theory, the book contains tests, exercises and useful illustrations - everything you need to learn Python 2 and 3. In addition, you will get acquainted with some advanced features of the language that not many specialists have mastered yet.

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

    This book will take you through the basics of the language quickly and in a fun way, before moving on to exception handling, web development, working with SQL, data processing, and Google App Engine. You will also learn how to write Android applications and much more about the power that Python gives you.

    Another award-winning Python book with 52 specially curated exercises for language learning. By examining them, you will understand how the language works, how to write programs correctly, and how to fix your own mistakes. The following topics are covered:

    • Setting up the environment;
    • Organization of the code;
    • Basic mathematics;
    • Variables;
    • Strings and text;
    • Interaction with users;
    • Working with files;
    • Loops and logic;
    • Data structures;
    • Software development;
    • Inheritance and composition;
    • Modules, Classes and Objects;
    • Packages;
    • Debugging;
    • Test automation;
    • Game development;
    • Web development.

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

    Python Programming for Beginners is a great place to start. It is a comprehensive guide written specifically for beginners who want to master the language. With the basics, you will move on to object-oriented programming and CGI scripting for processing web form data, and how to create graphical windowed applications and distribute them to other devices.

    This tutorial will walk you through all the steps from installing the interpreter to running and debugging full-fledged applications.

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

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

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

    A Python learning book with tons of practical examples.

    Practical examples can be found in our section. For example, read our on self-implementing zip function.

    The purpose of this book is to acquaint the reader with popular tools and various coding guidelines adopted in the open source community. The basics of the Python language are not covered in this book, because it is not about that at all.

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

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

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

    For advanced

    If you are looking to migrate to Python 3 or properly update your old code written in Python 2, then this book is for you. And also for you - to translate a project from Python 2 to Python 3 without pain.

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

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

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

    The book covers Python 3 in detail: data types, operators, conditions, loops, regular expressions, functions, object-oriented programming tools, working with files and directories, frequently used modules of the standard library. In addition, the book also focuses on the SQLite database, the interface for accessing the database, and how to get data from the Internet.

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

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

    As the name suggests, the purpose of this book is to provide the most complete concept of the Django web application development framework. Due to the fact that the book was published in Russian back in 2010, it considers an outdated version of the framework, Django 1.1. Still, this book is highly recommended as it provides a basic introduction to Django. And there are practically no good books on this framework in Russian, except for this one.

    Authors Adrian Golovaty and Jacob Kaplan-Moss take a close look at the components of the framework. The book contains a lot of material on developing Internet resources in Django, from the basics to such special topics as PDF and RSS generation, security, caching, and internationalization. It is recommended that you master the basic concepts of web development before reading this book.

    Game development

    Making Games with Python & Pygame is a book about the Pygame game development library. Each chapter provides the complete source code for the new game and detailed explanations of the development principles used.

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

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

    Data analysis and machine learning

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

    • Explore concepts such as NumPy arrays, SciPy methods, signal processing, Fast Fourier transforms, and hash tables;
    • get acquainted with abstract models of complex physical systems, fractals and Turing machines;
    • explore scientific laws and theories;
    • analyze examples of complex tasks.

    This book discusses Python as a tool for solving computationally intensive tasks. The goal of this book is to teach the reader how to use the Python data mining stack to efficiently store, manipulate, and understand data.

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

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

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

    You will also learn how to measure data over time and solve analytical problems in many areas of science.

    This book invites you to explore various methods for analyzing data using Python. Here's what you'll learn after reading:

    • manage data;
    • solve data science problems;
    • create high-quality renderings;
    • apply linear regressions to assess relationships between variables;
    • create recommendation systems;
    • handle big data.

    This tutorial explains the principles of natural language processing in simple terms. You will learn how to write programs that can handle large sets of unstructured text, gain access to vast datasets, and become familiar with basic algorithms.

    Other

    If you've ever renamed files for hours or updated hundreds of table cells, you know how exhausting it is. Do you want to learn how to automate such processes? The book "Automate the Boring Stuff with Python" explains how to create programs that will solve various mundane tasks in minutes. After reading, you will learn how to automate the following processes:

    • search for a given text in files;
    • creating, updating, moving and renaming files and folders;
    • searching and downloading data on the web;
    • updating and formatting data in Excel tables;
    • splitting, merging and encrypting PDF files;
    • distribution of letters and notifications;
    • filling out online forms.

    An excellent book with a minimal threshold of entry. It talks more about biology than language, but it will definitely come in handy for everyone working in this field. Equipped with a large number of disassembled examples of varying complexity.

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

    "Hacking Secret Ciphers with Python" not only tells about the history of existing ciphers, but also teaches you how to create your own programs to encrypt and break ciphers. An excellent book for learning the basics of cryptography.

    Share useful Python books in the comments!

    Top related articles