Python syntax basics. Python programming language


Introduction


Due to 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 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 a relatively new language Python programming(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 of a large number of modules connected to the program, providing 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, it was necessary 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 followed by 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 the features of Python 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 - 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 a file object opened 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 who use computer 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 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)

    This material is intended for those who are already familiar with programming and want to master the Python programming language. It is designed to show you in 10 minutes the features of the Python language, syntax features and the basic principles of working with Python using examples. There is no “water” here - information that is not directly related to the programming language. Let's begin!

    The Python programming language is strongly typified (Strong typing is distinguished by the fact that the language does not allow mixing different types in expressions and does not perform automatic implicit conversions, for example, you cannot subtract a set from a string), it is used dynamic typing— all types are determined during program execution.

    Declaring variables is optional, names are case sensitive (var and VAR are two different variables).

    Python is an object-oriented language; everything in the language is an object.

    Getting help

    Help (help) in Python is always available right in the interpreter. If you want to know how an object works, call help( ). Another useful instruction is dir() , which shows all the methods of an object, and the properties of objects .__doc__ which will show you the docstring:

    >>> help(5) Help on int object: (etc etc) >>> dir(5) ["__abs__", "__add__", ...] >>> abs.__doc__ "abs(number) -> number Return the absolute value of the argument."

    Python Syntax

    Python does not have constructs for ending blocks (such as class or function declarations, for example)—blocks are defined using indentation. Increase the indentation at the beginning of the block, decrease it at the end of the block. Statements that require indentation are terminated with a colon (:). If you don't yet have code after the start-of-block statement, insert a pass statement to pass the syntax check.

    While rangelist == 1: pass

    Single-line comments begin with a hash character (#), while multi-line comments use (""") at the beginning and end of the comment.

    Values ​​are assigned using the equal sign (“=”) (objects are actually named in the process).

    The difference test is performed with two equal symbols ("==").

    You can increase a value using the += operator and decrease it with -= by specifying a variable on the left side and the value by which the increase/decrement will occur on the right. This works with many data types in Python, including strings.

    You can assign a value to multiple variables on the same line. Examples:

    >>> myvar = 3 >>> myvar += 2 >>> myvar 5 >>> myvar -= 1 >>> myvar 4 """This is a multiline comment. The following lines concatenate the two strings.""" >>> mystring = "Hello" >>> mystring += " world." >>> print mystring Hello world. # This swaps the variables in one line(!). # It doesn't violate strong typing because values ​​aren't # actually being assigned, but new objects are bound to # the old names. >>> myvar, mystring = mystring, myvar

    Data Types in Python

    Python provides data types such as lists, tuples, and dictionaries. Sets are also available, using the sets module in versions prior to Python 2.5 and built into the language in later versions.

    Lists are similar to one-dimensional arrays. It is possible to have a list consisting of other lists.

    Dictionaries are associative arrays in which data is accessed by key.

    Tuples are immutable one-dimensional arrays.

    "Arrays" in Python can be of any type, meaning you can combine numbers, strings, and other data types in lists/dictionaries/tuples.

    The index of the first element is 0. A negative index value starts counting from last to first, [-1] will point to the last element.

    Variables can point to functions.

    >>> sample = , ("a", "tuple")] >>> mylist = ["List item 1", 2, 3.14] >>> mylist = "List item 1 again" # We"re changing the item . >>> mylist[-1] = 3.21 # Here, we refer to the last item. >>> mydict = ("Key 1": "Value 1", 2: 3, "pi": 3.14) >>> mydict["pi"] = 3.15 # This is how you change dictionary values. >>> mytuple = (1, 2, 3) >>> myfunction = len >>> print myfunction(mylist) 3

    You can get a slice of an array (list or tuple) by using a colon (:). Leaving the starting index value empty will indicate starting from the first value; leaving the end index empty value will indicate the last element of the array. Negative indices are counted backwards from the end of the array (-1 will point to the last element).

    Look at the examples:

    >>> mylist = ["List item 1", 2, 3.14] >>> print mylist[:] ["List item 1", 2, 3.1400000000000001] >>> print mylist ["List item 1", 2] > >> print mylist[-3:-1] ["List item 1", 2] >>> print mylist # Adding a third parameter, "step" will have Python step in # N item increments, rather than 1. # E.g. , this will return the first item, then go to the third and # return that (so, items 0 and 2 in 0-indexing). >>> print mylist[::2] ["List item 1", 3.14]

    Strings in Python

    An apostrophe (‘) or double quotes(double quote - "). This allows you to have quotation marks within a string indicated by apostrophes (for example, ‘He said “hello.”’ is a valid string).

    Multiline strings are denoted by using a triple apostrophe or quotation marks ("""). Python supports unicode out of the box. However, the second version of Python uses the (u) character to denote a string containing unicode: u"This is a unicode string." Python3 all strings contain Unicode.If in Python3 you need a sequence of bytes, which was essentially a string in previous versions, the symbol (b) is used: b"This is a byte string".

    To substitute parameter values ​​into a string, use the (%) operator and a tuple. Each %s is replaced by an element from the tuple, from left to right. You can also use a dictionary to substitute named parameters:

    >>>print "Name: %s\ Number: %s\ String: %s" % (myclass.name, 3, 3 * "-") Name: Poromenos Number: 3 String: --- strString = """ This is a multiline string.""" # WARNING: Watch out for the trailing s in "%(key)s". >>> print "This %(verb)s a %(noun)s." % ("noun": "test", "verb": "is") This is a test.

    Flow control instructions - if, for, while

    If, for, and while statements are used to control the order in which a program is executed. There is no switch or case in Python; if is used instead. For is used to iterate through the elements of a list (or tuple). To get a sequence of numbers, use range( ) . To interrupt the execution of a loop, break is used.

    The syntax for this construct is as follows:

    Rangelist = range(10) >>> print rangelist for number in rangelist: # Check if number is one of # the numbers in the tuple. if number in (3, 4, 7, 9): # "Break" terminates a for without # executing the "else" clause. break else: # "Continue" starts the next iteration # of the loop. It"s rather useless here, # as it"s the last statement of the loop. continue else: # The "else" clause is optional and is # executed only if the loop didn't "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 in Python

    Functions are declared using keyword"def". Optional arguments appear in the function declaration after the required ones and are assigned a default value. When calling a function, you can pass arguments by specifying their name and value, while skipping the part optional arguments or by arranging them in an order different from that declared in the function.

    Functions can return a tuple and using tuple unboxing you can return multiple values.

    Lambda functions are special functions that process a single argument.

    Parameters are passed via reference. By adding elements to the passed list you will receive an updated list outside the function. In this case, assigning a new value to parameters inside a function will remain a local action. Since passing only transfers the memory location, assigning a new object to a parameter as a variable will cause a new object to be created.

    Code examples:

    # Same as def funcvar(x): return x + 1 funcvar = lambda x: x + 1 >>> print funcvar(1) 2 # an_int and a_string are optional, they have default values ​​# if one is not passed (2 and "A default string", respectively). def passing_example(a_list, an_int=2, a_string="A default string"): a_list.append("A new item") an_int = 4 return a_list, an_int, a_string >>> my_list = >>> my_int = 10 >> > print passing_example(my_list, my_int) (, 4, "A default string") >>> my_list >>> my_int 10

    Python classes

    Python supports a limited form of multiple inheritance in classes.

    Private variables and methods can be declared (by convention, this is not checked by the interpreter) using two underscores at the beginning and no more than one at the end of the name (eg: "__spam").

    We can also assign arbitrary names to class instances. View examples:

    Class MyClass(object): common = 10 def __init__(self): self.myvariable = 3 def myfunction(self, arg1, arg2): return self.myvariable # This is the class instantiation >>> classinstance = MyClass() >> > classesinstance.myfunction(1, 2) 3 # This variable is shared by all classes. >>> classinstance2 = MyClass() >>> classinstance.common 10 >>> classinstance2.common 10 # Note how we use the class name # instead of the instance. >>> MyClass.common = 30 >>> classinstance.common 30 >>> classinstance2.common 30 # This will not update the variable on the class, # instead it will bind a new object to the old # variable name. >>> classinstance.common = 10 >>> classinstance.common 10 >>> classinstance2.common 30 >>> MyClass.common = 50 # This has not changed, because "common" is # now an instance variable. >>> classinstance.common 10 >>> classinstance2.common 50 # This class inherits from MyClass. The example # class above inherits from "object", which makes # it what"s called a "new-style class". # Multiple inheritance is declared as: # class OtherClass(MyClass1, MyClass2, MyClassN) class OtherClass(MyClass): # The "self" argument is passed automatically # and refers to the class instance, so you can set # instance variables as above, but from inside the class. def __init__(self, arg1): self.myvariable = 3 print arg1 >> > classinstance = OtherClass("hello") hello >>> classinstance.myfunction(1, 2) 3 # This class doesn't have a .test member, but # we can add one to the instance anyway. Note # that this will only be a member of classinstance. >>> classinstance.test = 10 >>> classinstance.test 10

    Exceptions in Python

    Exceptions in Python are handled in try-except blocks:

    Def some_function(): try: # Division by zero raises an exception 10 / 0 except ZeroDivisionError: print "Oops, invalid." else: # Exception didn't occur, we're good. pass finally: # This is executed after the code block is run # and all exceptions have been handled, even # if a new exception is raised while handling. print "We"re done with that." >>> some_function() Oops, invalid. We"re done with that.

    Importing modules in Python

    External libraries are used after import using the import keyword. You can also use from import to import custom functions.

    Import random from time import clock randomint = random.randint(1, 100) >>> print randomint 64

    Working with Files in Python

    Python has a large number of libraries for working with files. For example, serialization (converting data to strings with the pickle library):

    Import pickle mylist = ["This", "is", 4, 13327] # Open the file C:\\binary.dat for writing. The letter r before the # filename string is used to prevent backslash escaping. myfile = open(r"C:\\binary.dat", "w") pickle.dump(mylist, myfile) myfile.close() myfile = open(r"C:\\text.txt", "w" ) myfile.write("This is a sample string") myfile.close() myfile = open(r"C:\\text.txt") >>> print myfile.read() "This is a sample string" myfile .close() # Open the file for reading. myfile = open(r"C:\\binary.dat") loadedlist = pickle.load(myfile) myfile.close() >>> print loadedlist ["This", "is", 4, 13327]

    Miscellaneous

    • Conditions can stick together, for example 1< a < 3 проверит, что a одновременно меньше 3 и больше 1.
    • You can use del to remove variables or elements in arrays.
    • Lists provide very powerful data manipulation capabilities. You can make an expression with using for and subsequent if or for statements:
    >>> lst1 = >>> lst2 = >>> print >>> print # Check if a condition is true for any items. # "any" returns true if any item in the list is true. >>> any()) True # This is because 4 % 3 = 1, and 1 is true, so any() # returns True. # Check for how many items a condition is true. >>> sum(1 for i in if i == 4) 2 >>> del lst1 >>> print lst1 >>> del lst1
    • Global variables are declared outside functions and can be read without special declarations inside, but if you want to write them out, you must declare from at the beginning of the function using the special "global" keyword, otherwise Python will assign the new value to the local variable:
    number = 5 def myfunc(): # This will print 5. print number def anotherfunc(): # This raises an exception because the variable has not # been bound before printing. Python knows that it an # object will be bound to it later and creates a new, local # object instead of accessing the global one. print number number = 3 def yetanotherfunc(): global number # This will correctly change the global. number = 3

    How to Learn the Python Programming Language

    This material is not intended to be a comprehensive guide to Python. The Python programming language has a huge number of libraries and various functionality that you will become familiar with as you continue to work with the language and study additional sources.

    If the information presented is not enough for you, look at the extended material describing the Python programming language - it provides information about the language in more detail.

    Among other materials, I recommend Learn Python The Hard Way. And, of course, The Python 2 Tutorial and The Python 3 Tutorial.

    Many thanks to Stavros Korokithakis for his excellent tutorial “Learn Python in 10 minutes”.

    If you want to improve something in this material, please write in the comments.

    August 27, 2012 at 03:18 pm

    Learn Python efficiently

    • Python

    Hello everyone!

    Human-readable syntax, easy to learn, high-level language, Object-Oriented programming language (OOP), powerful, interactive mode, a lot of libraries. Many other advantages... And all this in one language.
    First, let's dive into the possibilities and find out what Python can do?

    Why do I need your Python?

    Many new programmers ask similar questions. It's like buying a phone, tell me why should I buy this phone and not this one?
    Software quality
    For many, including me, the main advantages are the human-readable syntax. Not many languages ​​can boast of it. Python code is easier to read, which means reusing and maintaining it is much easier than using code in other scripting languages. Python contains the most modern mechanisms for reusing program code, which is OOP.
    Support Libraries
    Python comes with a large number of compiled and portable functionality known as the standard library. This library provides you with a lot of features that are in demand in application programs, ranging from text search by pattern to network functions. Python can be extended both by your own libraries and by libraries created by other developers.
    Program portability
    Most Python programs run unchanged on all major platforms. Transferring program code from Linux to Windows involves simple copying program files from one machine to another. Python also gives you a lot of opportunities to create portable graphical interfaces.
    Development speed
    Compared to compiled or strongly typed languages ​​such as C, C++ or Java, Python increases developer productivity many times over. Python code is typically one-third or even one-fifth the size of equivalent C++ or Java code, which means less typing, less debugging time, and less maintenance effort. Additionally, Python programs run immediately without the time-consuming compilation and linking steps required in some other programming languages, further increasing programmer productivity.

    Where is Python used?

    • Google uses Python in its search engine and pays for the work of the creator of Python - Guido van Rossum
    • Companies such as Intel, Cisco, Hewlett-Packard, Seagate, Qualcomm and IBM use Python for hardware testing
    • YouTube's video sharing service is largely implemented in Python
    • NSA uses Python for encryption and intelligence analysis
    • JPMorgan Chase, UBS, Getco and Citadel use Python for financial market forecasting
    • The popular BitTorrent program for exchanging files on peer-to-peer networks is written in Python
    • Popular web framework App Engine from Google uses Python as an application programming language
    • NASA, Los Alamos, JPL, and Fermilab use Python for scientific computing.
    and other companies also use this language.

    Literature

    So we got to know the Python programming language better. We can say separately that the advantages of Python are that it has a lot of high-quality literature. Not every language can boast of this. For example, the JavaScript programming language cannot please users with a lot of literature, although the language is really good.

    Here are sources that will help you get to know Python better, and maybe become the future Guido van Rossum.
    * Some sources may be in English. You shouldn’t be surprised by this, now a lot of excellent literature is written in English language. And for programming itself you need to know at least basic knowledge of English.

    I highly recommend reading the book first - Mark Lutz. Learning Python, 4th Edition. The book has been translated into Russian, so don’t be afraid if you suddenly don’t know English. But it is the fourth edition.

    For those who know English, you can read the documentation on the official Python website. Everything is described there quite clearly.

    And if you prefer information from video, then I can recommend lessons from Google, taught by Nick Parlante, a student from Stanford. Six video lectures on YouTube. But there is a drop of ointment in the barrel of ointment... He conducts it in English with English subtitles. But I hope that this will stop a few.

    What should I do if I read books, but don’t know how to apply the knowledge?

    Don't panic!
    I recommend reading the book by Mark Lutz. Python Programming (4th Edition). Previously it was “studying”, but here it is “Programming”. In “Learning” - you gain knowledge of Python, in “Programming” - Mark teaches you how to apply it in your future programs. The book is very useful. And I think one is enough for you.

    I want practice!

    Easily.
    Above I wrote about video lectures from Nick Parlante on YouTube, but they also have some

    What programs are written in Python?

    Application software for normal people

    Let's first go through the programs that are used by ordinary people who are not specialists in the field of information technology.

    BitTorrent

    All versions up to 6 of this torrent client were written in Python. Version 6 was rewritten in C++.

    Ubuntu Software Center

    Quote from Wikipedia:
    Ubuntu Application Center(English) Ubuntu Software Center) is free software for finding, installing and removing packages on an Ubuntu Linux system. V latest versions You can purchase magazines about Linux and Ubuntu, you can also purchase paid games and software. The application is developed in Python + Vala using GTK+ libraries and is a graphical shell for the Advanced Packaging Tool.

    Blender

    Quote from Wikipedia:
    Blender- a free, professional package for creating three-dimensional computer graphics, which includes tools for modeling, animation, rendering, video post-processing, and creating interactive games. Currently, it is the most popular among free 3D editors due to its rapid and stable development, which is facilitated by a professional development team.

    Python is used as a tool for creating tools and prototypes, logic systems in games, as a means of importing/exporting files (for example COLLADA), and automating tasks.

    Here are some documentation pages:

    GIMP

    Quote from Wikipedia:
    Python is used to write additional modules, such as filters.
    Here are a few pages that go deeper into the topic:

    Games

    Civilization IV

    Most of the game is written in Python().

    Battlefield 2

    There are many tutorials and simple recipes on the Internet for changing various objects and their behavior.

    World of Tanks

    Quote from the article "GUI in the game World of Tanks":
    Python is used as the scripting language in the project. All the beauty that we made in Flash needs to be connected in the game, filled with data, processed and translated into real actions in the game. All this is done in Python.
    A more comprehensive list of games that use Python can be found on Wikipedia and the Python documentation.

    What companies use Python?

    The list of companies that use Python is long. Among them are Google, Facebook, Yahoo , NASA , Red Hat , IBM , Instagram , Dropbox, Pinterest, Quora, Yandex, Mail.Ru.

    Yandex

    Here you go, the report “Python in the core of Yandex.Disk”. Sergey Ivashchenko (speaker):
    I will talk about how we use Python in Yandex.Disk, what libraries and frameworks we use, what tasks we solve and what problems we encounter. I will also touch on the topic of logging and processing asynchronous operations.
    In one of the videos on the Yandex channel, employees talked about their favorite languages.

    And on the Yandex company blog there is an entry “What programming languages ​​are written in Yandex” dated March 19, 2014. So, 13% of Yandex employees write most of their working time in Python.

    Mail.ru

    Mail.ru employees also use Python. The official Mail.ru blog on Habré has several articles about Python:

    Google

    Google has been actively using Python since its founding. There are rumors that most of YouTube and Google Drive written in Python. Google has developed an entire cloud platform, Google App Engine, so that developers can run Python code on the Google cloud. Many language developers have worked and are working at Google.

    DropBox

    The service is developed in Python. It is no coincidence that the author of the Python language, Guido van Rossum, works at DropBox.

    Other companies

    The organizations that use Python

    What areas is Python used in?

    Web development

    Python is perhaps the most used in this area. The Django web framework continues to gain momentum, expanding its army of fans. Many novice programmers even think that Python is not used anywhere else. But many other web frameworks are written in Python: Pylons TurboGears , CherryPy, Flask, Pyramid and others. You can find a more complete list.
    There is also a CMS based on Django, it is called DjangoCMS.
    Very often, website parsers are written in Python. Typically Requests, aiohttp, BeautifulSoup, html5lib are used for this. There are also higher-level tools for website parsing: Scrapy, Grab.

    System administration

    Python is a great language for automating work system administrator. It is installed by default on all Linux servers. It is simple and understandable. Python code is easy to read. Some people love Perl, I also love it for its convenient work with regular expressions but I hate Perl for its syntax. Bash is useful for relatively small to medium-sized scripts, but Python is more powerful and in some cases allows you to write much less code.
    The only package I know of is Fabric. Perhaps there is something else, write me in the comments if you know.

    Additional Information

    Python for system administrators (IBM developerWorks)
    Fabric documentation. Systems Administration.

    Embedded systems

    Python is very often used for programming embedded systems. The most famous project that uses Python is the Raspberry Pi. But he's not the only one:
    Embedded Python
    Raspberry Pi
    Python Embedded Tools
    The Owl Embedded Python System

    Application software development, including games

    Python is often used as a supporting language in application software development. I have already given examples above, I will not repeat them.

    Scientific research

    Physicists and mathematicians love Python for its simplicity. In addition, there are a huge number of libraries for Python that make life easier for a scientist. For example:
    1. SciPy is an open library of high-quality scientific tools for the Python programming language. SciPy contains modules for optimization, integration, special functions, signal processing, image processing, genetic algorithms, solving ordinary differential equations, and other problems commonly solved in science and engineering.
    2. Matplotlib- a library in the Python programming language for visualizing data with two-dimensional (2D) graphics (3D graphics are also supported). The resulting images can be used as illustrations in publications.
    3. NumPy is an extension of the Python language that adds support for large multidimensional arrays and matrices, along with a large library of high-level mathematical functions for operating on these arrays.
    A more comprehensive list of libraries for scientific computing in Python can be found on Wikipedia.

    Education

    Python is often recommended as the first programming language.
    Some Russian schools have successful experience in teaching schoolchildren programming in Python.
    By the way, Guido van Rossum was impressed by the ABC language when he wrote Python. And the ABC language was intended for training and prototyping.

    Criticism of the Python language

    Python is one of the slowest programming languages

    On the Internet you can find many different speed tests for programs written in different programming languages. Python is usually at the end of lists.
    Typically, Python refers to CPython, the reference implementation of the language. There are other implementations of the Python language, such as PyPy. PyPy is faster than CPython and many other scripting programming languages, and is very close to Java in speed. But there is one problem - PyPy does not fully implement the Python language, because of this, many Python programs do not work on it.
    Many programmers write inserts in C/C++ to speed up work in bottlenecks. Python is not designed for computational tasks, for tasks that require a lot of memory (memory bound) and the like. You need to be able to choose the right tools for the tasks you face. Guido van Rossum talks about this in an interview.

    GIL prevents multiple threads from executing simultaneously

    Global Interpreter Lock prevents multiple Python threads from executing simultaneously. These are features of CPython. But is this a disadvantage? You need to understand that everything depends on the task. If your task depends on the I/O speed (IO bound task), then it is more efficient to use several processes that will work asynchronously with external resources. And shared memory threads are good for computing tasks (CPU-bound). But even if you need to work with threads, you can disable the GIL for a while, since this is done in the NumPy mathematical package.

    No good distribution tools

    Unfortunately, Python code, which has many dependencies on system libraries, is difficult to port to other systems. This problem is solved using virtualenv. but this tool is criticized a lot by system administrators.

    Additional Information

    Python Success Stories
    You Used Python to Write WHAT?
    What is Python Used For?
    More proof that it"s Python"s world and we"re just living in it
    AVERAGE SALARY FOR JOBS REQUIRING PYTHON
    List of Python software




    

    2024 gtavrl.ru.