Python programming language for beginners to read. Python programming language for beginners


Since I started teaching Python in 2011, I have found several resources that I use regularly. When I first started learning the language, I was surprised at how welcoming the Python community was. The proof of this is great amount free high quality materials. Below I will give examples of those resources that simply would not exist without the support of the community.

1. Invent Your Own Computer Games With Python

You may already have your own favorite Python book, but I encourage you to read this one. You can purchase it, read it online, or download it for free in PDF. I like the same structure of the chapters: first the problem is posed, and then there are examples of solutions to problems with detailed explanations. The same author wrote 3 more wonderful books.

2. Skulpt

I've worked in schools where for one reason or another (usually security reasons) Python was not available. Skulpt runs Python scripts in the browser and includes several examples. The first one uses the Turtle module to output geometric shapes. I often use it to test students' knowledge.

3. Guess the number

8. Random

Python has several useful built-in functions, such as print and input. The random module, on the other hand, needs to be imported before use. It allows students to add a little unpredictability to their projects.

Import random coin = [‘heads’,’tails’] flip = random.choice(coin) print(flip)

9.Anti Gravity

I rarely use the anti gravity module. But when I have to do this, I ask the students what will happen when they import it. Usually I get many different answers, sometimes they even suggest that the real effect of weightlessness will begin - they think that Python is so powerful :) You can try it yourself and offer it to your students.

Import antigravity

10. Sabotage

The biggest difficulty for me as a teacher was finding syntax errors in student programs. Luckily, before I completely burned out from exhaustion, I came up with

How many programming languages ​​are there really? There are several dozen of them. They are designed for various tasks, for every taste, size and color. Why did I choose this particular language? Python is capable of performing a very wide range of tasks, ranging from a simple script to creating entire websites. Python for beginners is quite simple, concise and easy to learn.

From this article you will learn:

Hi Hi! Gridin Semyon is in touch. Finally, I got to the main topic of this blog, programming intelligent systems using the Python language. I've been preparing for this for a long time. And now I'm ready to write to you interesting articles and study this topic in depth.

Why do I need this? To begin with, I set myself the following task about the development of machine learning and computer vision.

Maybe if I'm lucky, I'll end up among the developers of complex robotic projects, maybe I'll become an organizer myself and open the production of personal robots, or maybe, maybe... If nothing works out, and God bless him, I enjoy the process, not the result.

Then I’ll start my story))...

Features of the Python programming language

As I wrote above, this language performs very large sphere functions. It is simply impossible to cover everything. Therefore, before you study, please ask yourself the question, why do I need this? What problems will I solve using this language? If you answered positively, move on.

How can Python be useful?

  1. Working with xml/html files
  2. Working with http requests
  3. GUI (graphical interface)
  4. Creating web scripts
  5. Working with FTP
  6. Working with images, audio and video files
  7. Robotics (use of single board computers)
  8. Mathematical and Scientific Computing Programming

Etc. Python is capable of performing the lion's share of routine tasks.

In Python you can build and backup, and work with by email, And simple calculator, and a script for the site. The language is not limited by anything. What’s most interesting is that it is used by such IT giants as Google and Yandex.

In this article we will walk you through Python programming from scratch.

In order for your program to work on specific device, no matter what OS - windows, linux, RaspbianOS, MacOS. It is important that you have an interpreter that will understand the commands and execute them.

Do the following: download python IDE c official source.

Getting to know the interpreter

So the interpreter processes text code programs. There is an interactive development environment mode. You can run it in several ways:

  1. From a regular cmd command line, enter the command python ;
  2. From desktop (shortcut);
  3. Using the Start menu - Python IDLE;

This window will open for you:

By the way, the shell can also be used as a regular calculator. I see this software as an opportunity to unlock the full potential of single board computers.

There is also one for Arduino shell. Read it.

Where to begin python training? Let's try to write the first program?

Creating the first program

Program for Python language is a regular text file with written code. The extension of this file is .py. You can run the program by specifying the appropriate name on the command line. Let's write the simplest one standard program"Hello world!"

The task is to display “Hello world!” on the screen. Launch NotePad.

We write the following code:

Python

print("Hello world!!!")

print("Hello world!!!" )

And save it to a folder following the path C:\MyScripts. I recommend putting all projects in this folder.

In order for us to run the script, select command line and enter the path to your file:

About books. In fact, although the language is simple in terms of creating code, there are a lot of nuances and various libraries for implementing a huge range of tasks.

The best book on python for beginners is considered to be Mike McGrath's tutorial. Comprehensive Guide on writing code in Python.

Sorry for the photo quality, it doesn't work any other way. I don’t recommend buying the other books yet, as they are actually bulky and voluminous. McGrath will suffice as a basis.

Guys, that's all for me, if you have any questions, you can always write to me. Subscribe to blog news. Send it to your friends. Thank you for your attention.

Best regards, Gridin Semyon

(Translation)

An article was published on the Poromenos Stuff website in which, in a concise form, they talk about the basics of the Python language. I offer you a translation of this article. The translation is not literal. I tried to explain in more detail some points that may not be clear.

If you are planning to learn Python, but cannot find a suitable guide, then this article will be very useful to you! In a short time, you will be able to get acquainted with the basics of the Python language. Although this article often relies on you already having programming experience, I hope even beginners will find this material useful. Read each paragraph carefully. Due to the condensation of the material, some topics are discussed superficially, but contain all the necessary material.

Basic properties

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

Syntax

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

To assign a value to a variable, the “=” sign is used, and for comparison, “==” is used. To increase the value of a variable, or add to a string, use the “+=” operator, and “-=” to decrease it. All of these operations can interact with most types, including strings. For example

>>> myvar = 3

>>> myvar += 2

>>> myvar -= 1

"""This is a multi-line comment

Strings enclosed in three double quotes are ignored"""

>>> mystring = "Hello"

>>> mystring += "world."

>>>print mystring

Hello world.

# Next line changes

The values ​​of the variables are swapped. (Just one line!)

>>> myvar, mystring = mystring, myvar

Data structures

Python contains data structures such as lists, tuples and dictionaries). Lists are similar to one-dimensional arrays (but you can use a List containing lists - a multidimensional array), tuples are immutable lists, dictionaries are also lists, but indexes can be of any type, not just numeric. "Arrays" in Python can contain data of any type, that is, one array can contain numeric, string, and other data types. Arrays start at index 0 and the last element can be obtained at index -1 You can assign function 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 fractional number

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

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

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

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

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

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

>>> print myfunction(mylist)

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

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

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

["List item 1", 2, 3.1400000000000001]

>>> print mylist #The zeroth and first elements of the array are read.

["List item 1", 2]

>>> print mylist[-3:-1] #Elements from zero (-3) to second (-1) are read (not inclusive)

["List item 1", 2]

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

Strings

Strings in Python separated by double quotes """ or single quotes """. Double quotes may contain single quotes, or vice versa. For example, the line “He said hello!” will be displayed as "He said hi!". If you need to use a string of several lines, then this line must begin and end with three double quotes """". You can substitute elements from a tuple or dictionary into the string template. The percent sign "%" between the string and the tuple replaces characters in the string "%s" to a tuple element. Dictionaries allow you to insert an element at a given index into a string. To do this, use the construction "%(index)s" in the string. In this case, instead of "%(index)s" the dictionary value at the given index will be substituted index.

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

Name: Poromenos

Number: 3

String: ---

strString = """This text is located

on several lines"""

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

This is a test.

Operators

The while, if, and for statements constitute move operators. There is no analogue here select statement, so you'll have to make do with if . The for statement makes a comparison variable and list. To get a list of digits up to a number - use the range( function ). Here is an example of using operators

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

>>> print rangelist

for number in rangelist: #As long as the variable number (which is incremented by one each time) is in the list...

# Check if the variable is included

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

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

# The "break" operation provides

# exit the loop at any time

Break

Else:

# "continue" performs "scrolling"

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

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

Continue

else:

# "else" is optional. The condition is met

# if the loop was not interrupted with "break".

Pass # Do nothing

if rangelist == 2:

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

elif rangelist == 3:

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

else:

Print "Dunno"

while rangelist == 1:

Pass

Functions

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

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

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

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

Return arg3, arg2, arg1

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

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

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

>>> print ret1, ret2, ret3

Named argument 100 Argument 1

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

functionvar = lambda x: x + 1

>>> print functionvar(1)

Classes

The Python language is limited in multiple inheritance in classes. Internal variables and internal methods of classes begin with two characters underscore"__" (for example "__myprivatevar"). We can also assign a value class variable from outside. Example:

class Myclass:

Common = 10

def __init__(self):

Self.myvariable = 3

Def myfunction(self, arg1, arg2):

Return self.myvariable

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

>>> classinstance = Myclass() # We have initialized the class and myvariable has the value 3 as stated in the initialization method

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

# The common variable is declared in all classes

>>> classesinstance2 = Myclass()

>>> classesinstance.common

>>> classinstance2.common

# So if we change its value in the Myclass class it will change

# and its values ​​in objects initialized by the Myclass class

>>> Myclass.common = 30

>>> classesinstance.common

>>> classinstance2.common

# And here we do not change the class variable. Instead of this

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

>>> classinstance.common = 10

>>> classesinstance.common

>>> classinstance2.common

>>> Myclass.common = 50

# Now changing the class variable will not affect

# variable objects of this class

>>> classesinstance.common

>>> classinstance2.common

# The following class is a descendant of the Myclass class

# by inheriting its properties and methods, who can the class

# inherit from several classes, in this case the entry

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

class Otherclass(Myclass):

Def __init__(self, arg1):

Self.myvariable = 3

Print arg1

>>> classinstance = Otherclass("hello")

hello

>>> classesinstance.myfunction(1, 2)

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

# declare such a variable for an object. Moreover

# this variable will be a member of classinstance only.

>>> classinstance.test = 10

>>> classesinstance.test

Exceptions

Exceptions in Python have a try -except structure:

def somefunction():

Try:

# Division by zero causes an error

10 / 0

Except ZeroDivisionError:

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

# And handles the exception block corresponding to the “ZeroDivisionError” error

Print "Oops, invalid."

>>> fnexcept()

Oops, invalid.

Import

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

import random #Import the “random” library

from time import clock #And at the same time the “clock” function from the “time” library

randomint = random.randint(1, 100)

>>> print randomint

Working with the file system

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

import pickle

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

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

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

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

pickle.dump(mylist, myfile)

myfile.close()

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

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

myfile.close()

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

>>> print myfile.read()

"This is a sample string"

myfile.close()

# Open the file for reading

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

loadedlist = pickle.load(myfile)

myfile.close()

>>> print loadedlist

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

Peculiarities

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

>>> lst1 =

>>> lst2 =

>>> print

>>> print

# The "any" operator returns true if although

# if one of the conditions included in it is satisfied.

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

True

# The following procedure counts the number

# matching elements in the list

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

>>> del lst1

>>> print lst1

>>> del lst1

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

number = 5

def myfunc():

# Outputs 5

Print number

def anotherfunc():

# This throws an exception because the global variable

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

# variable of the same name inside this function and accessible

# only for operators of this function.

Print number

Number = 3

def yetanotherfunc():

Global number

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

Number = 3

Epilogue

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

Benefits of Python

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

Introduction


Due to what is currently observed rapid development personal computing technology, there is a gradual change in the requirements for programming languages. Interpreted languages ​​are beginning to play an increasingly important role as the growing power personal computers begins to provide sufficient execution speed of interpreted programs. And the only significant advantage of compiled programming languages ​​is the high-speed code they produce. When program execution speed is not a critical value, the most the right choice there will be an interpreted language as a simpler and more flexible programming tool.

In this regard, it is of some interest to consider the 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, but is also very flexible and expressive. This is a higher-level language than Pascal, C++ and, of course, C, which is achieved mainly through built-in high-level data structures (lists, dictionaries, tuples).

Advantages of language.
An 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 to writing a truly portable program. Python does not have such a 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 it is possible for all interested programmers to improve the language. The interpreter is written in C and source 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 own additions to Python in C and compiling the program, you can get an “extended” interpreter with new capabilities.

The next advantage is the presence large number modules connected to the program that provide various additional features. Such modules are written in C and Python itself and can be developed by all sufficiently qualified programmers. Examples include the following modules:

  • Numerical Python - advanced mathematical capabilities such as manipulation of integer vectors and matrices;
  • Tkinter - building applications using a graphical user interface (GUI) based on the Tk interface widely used on X-Windows;
  • OpenGL - using an extensive library graphic modeling two- and three-dimensional objects Open Graphics Library from Silicon Graphics Inc. 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 language.
The only drawback noticed 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 execution speed.

Features Overview


1. Python, unlike many languages ​​(Pascal, C++, Java, etc.), does not require variable declarations. They are created at the place where they are initialized, i.e. the first time a variable is assigned a value. This means that the type of a variable is determined by the type of the assigned value. In this respect, Python resembles Basic.
The type of a variable is not immutable. Any assignment to 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++, organizing lists presented some difficulties. To implement them, one had to thoroughly study the principles of working with pointers and dynamic memory. And even with good qualifications, the programmer, each time re-implementing the mechanisms for creating, working and destroying lists, could easily make subtle errors. In view of this, some tools have been created for working with lists. For example, Delphi Pascal has a class TList that implements lists; The STL (Standard Template Library) library has been developed for C++, containing structures such as vectors, lists, sets, dictionaries, stacks and queues. However, such facilities are not available in all languages ​​and their implementations.

One of distinctive features Python is the presence of structures built into the language itself such as tuples(tuple) lists(list) and dictionaries(dictionary), which are sometimes called cards(map). Let's take a closer look at them.

  1. Tuple . It is somewhat reminiscent of an array: it consists of elements and has a strictly defined length. Elements can be any values ​​- simple constants or objects. Unlike an array, the elements of a tuple are not necessarily homogeneous. 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 cannot add new elements. Thus, a tuple can be called a constant list. Syntactically, a tuple is specified by listing all elements separated by commas, all 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 tuple name 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, a tuple could be called a constant vector if its elements were always homogeneous.
  3. List . A good, specific example of a list is the Turbo Pascal language string. The elements of a line are single characters, its length is not fixed, it is possible to delete elements or, on the contrary, insert them anywhere in the line. The elements of the list can be arbitrary objects, not necessarily of the same type. To create a list, just list its elements separated by commas, enclosing them all in square brackets:


  4. ['string', (0,1,8), ]
    Unlike a tuple, lists can be modified as desired. Access to elements is carried out in the same way as in tuples. Example:
    l = ]
    print l, l, l[-2], l[-1]
    Result: 1 s (2.8) 0
  5. Dictionary . It is reminiscent of the record type in Pascal or the structure type in C. However, instead of the “record field” - “value” scheme, “key” - “value” is used here. A dictionary is a collection of key-value pairs. Here the “key” is a constant of any type (but strings are mainly used), it serves to name (index) some corresponding value (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, after the dictionary name, write the corresponding key in square brackets. 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 key-value pair, simply 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 way it is similar to Java. As you know, pointers are a source of subtle errors, and working with them relates more to low-level programming. To provide greater reliability and simplicity, they were not included in Python.

4. One of Python features is how one variable is assigned to another, i.e. when on either side of the operator" = " there are variables.

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

When an assignment leads to the creation of a new object (here an object - 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 call this case copy semantics. Thus, if copy semantics applies when copying, then the variables on either side of the "=" sign will mean two independent objects with the same content. And here, a subsequent change in one variable will not affect the other in any way.

Assignment in Python works like this: if assignable the object is an instance of such types as numbers or strings, then copy semantics applies, but if on the right side there is an instance of a class, list, dictionary or tuple, then pointer semantics applies. 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's going on here, I'll give you a different take on assignment in Python. If in languages ​​such as Basic, Pascal, C/C++ we dealt with “capacity” variables and constants stored in them (numeric, symbolic, string - it doesn’t matter), and the assignment operation meant “entering” the constant into the assigned variable , then in Python we must already work with “name” variables and the objects they name. (You notice some analogy with Prolog language?) What is an object in Python? This is everything that can be given a name: numbers, strings, lists, dictionaries, class instances (which in Object Pascal are called objects), the classes themselves (!), functions, modules, etc. So, when assigning a variable to an object, the variable becomes its “name”, and the object can have as many such “names” as desired and they are all independent of each other.

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

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

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

  • This is how we get the “pseudo” semantics of pointers.

    One last thing to say about this: although it is not possible to change the structure of the tuple, the mutable components it contains are still available for modification:

    T = (1, 2, , "string") t = 6 # this is not possible 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 Python groups operators is very original. In Pascal, this is done using operator brackets begin-end, in C, C++, Java - curly braces (), in Basic, closing endings of language constructs are used (NEXT, WEND, END IF, END SUB).
    In Python, everything is much simpler: selecting a block of statements is carried out by shifting the selected group by one or more spaces or tab characters to the right relative to the head of the structure to which the given block will belong. For example:

    if x > 0: print ‘ x > 0 ’ x = x - 8 else: print ‘ x<= 0 ’ x = 0 Thus, a good style of writing programs, which teachers of the languages ​​Pascal, C++, Java, etc. call for, is acquired here from the very beginning, since it simply won’t work any other way.

    Description of the language. Control structures



    Exception Handling


    try:
    <оператор1>
    [except[<исключение> [, <переменная>] ]:
    <оператор2>]
    [else <оператор3>]
    Performed<оператор1>, if an exception occurs<исключение>, then it is fulfilled<оператор2>. If<исключение>has a value, it is assigned<переменной>.
    Upon successful completion<оператора1>, performed<оператор3>.
    try:
    <оператор1>
    finally:
    <оператор2>
    Performed<оператор1>. If no exceptions occur, then execute<оператор2>. Otherwise executed<оператор2>and an exception is immediately raised.
    raise <исключение> [<значение>] Throws an exception<исключение>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



    Class Declaration



    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 = " 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 s is replaced by x.
    s = t part of the elements s from i to j-1 is replaced by t (t can also be a list).
    del s removes the s part (same as s = ).
    s.append(x) adds 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 a string in reverse order
    s.sort() sorts the list in ascending order.

    Operators for dictionaries


    File objects


    Created by a built-in function open()(see description below). For example: f = open('mydan.dat','r').
    Methods:

    Other language elements and built-in functions


    = assignment.
    print [ < c1 > [, < c2 >]* [, ] ] displays values< c1 >, < c2 >to standard output. Places a space between arguments. If there is no comma at the end of the list of arguments, it moves to a new line.
    abs(x) returns absolute value x.
    apply( f , <аргументы>) calls function (or method) f with< аргументами >.
    chr(i) returns a one-character string with ASCII code i.
    cmp(x,y) returns negative, zero, or positive if, respectively, x<, ==, или >than y.
    divmod (a, b) returns tuple (a/b, a%b), where a/b is a div b (the integer part of the division result), a%b is a mod b (the remainder of the division).
    eval(s)
    returns the object specified in s as a string. S can contain any language structure. 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(<строка>) displays<строку>, reads and returns a value from standard input.
    int(x) returns the integer value of x.
    len(s) returns the length (number of elements) of an object.
    long(x) returns a long integer value x.
    max(s), min(s) return the largest and smallest element of the sequence s (that is, s is a string, list, or tuple).
    oct(x) returns a string containing a representation of the number x.
    open(<имя файла>, <режим>='r' ) returns file object, open for reading.<режим>= 'w' - opening for writing.
    ord(c) returns the ASCII code of a 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( [ <текст> ] ) displays<текст>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 (<начало>, <конец>, <шаг>) is similar to range, but only simulates a 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 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 that is initialized<начальным значением>, then, for each element<списка>, the function f is called with two parameters: p and the 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 a name and is written where it is called. Accepts the parameters specified in<списке параметров>, and returns the value<выражения>. Used for filter, reduce, map. For example: >>>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 use computer technology and programming in my 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 great interest to professional programmers who develop applications that are not critical to execution speed, as well as programs that use complex data structures. In particular, Python has proven itself well in developing programs for working with graphs and generating trees.

    Literature


    1. Budd T. Object-oriented programming. - St. Petersburg: 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)

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

    What to do?

    We looked through a lot of training materials and just good articles and made a list of what you need to learn in order to master this programming language and develop in it.

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

    2. Study literature. Start with the classic – Dive into Python. This book can actually become a reference book. You can also read Michael Dawson “Programming in Python” and Alexey Vasiliev “Python with examples. Practical programming course." Dawson is an experienced programmer and teacher, and in the book he teaches programming by creating simple games. In Vasiliev's book, on the contrary, more attention is paid to the fundamentals and theory.

    4. Take the Introduction to Computer techologies and Programming in Python" from MIT.

    5. Find out what libraries other Pythonists use and for what purposes. Find something interesting for yourself.

    6. If you are interested in web technologies, pay attention to the Flask and Django frameworks. Find out for what purposes which one is better suited, start studying the one that suits you.

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

    8. Look for information about machine learning methods.

    9. Optimize work with tools, automate routine and everything that is not yet automated.

    Where to go?

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

    Useful Resources

    Python Tutor

    This tool helps you overcome a fundamental barrier to understanding the programming language you're learning: by visualizing the code, this resource provides insight into what's happening as the computer executes each line of code.

    Bucky Roberts on YouTube

    If you are not familiar with programming, these tutorials will help you a lot. They are easy to understand and cover everything you might need first, starting with language installation.

    Derek Banas on Python on YouTube

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

    Corey Schafer on YouTube

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

    Django Getting Started

    Official documentation for the Django web framework. Covers everything you need to know when getting started, from setup to your first application.

    Introduction to Flask

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

    useful links

    Newbie

    Python 3 for Beginners
    "A Byte of Python"





    

    2024 gtavrl.ru.