Python

ImprimirCitar

Python is a high level interpreted programming language whose philosophy emphasizes the readability of its code, it is used to develop applications of all kinds, examples: Instagram, Netflix, Spotify, Panda3D, among others. It is a multiparadigm programming language, since it partially supports object orientation, imperative programming and, to a lesser extent[which one?], programming functional. It is an interpreted, dynamic and cross-platform language.

Managed by the Python Software Foundation, it is licensed under an open source license, called the Python Software Foundation License. Python consistently ranks as one of the most popular programming languages.

History

Guido van Rossum, creator of Pythonat the OSCON 2006 convention

Python was created in the late 1980s by Guido van Rossum at Stichting Mathematisch Centrum (CWI) in the Netherlands as a successor to the ABC programming language, capable of handling exceptions and interfacing with the Amoeba operating system..

The language's name comes from its creator's fondness for British comedians Monty Python.

Guido van Rossum is the leading author of Python, and his continuing central role in deciding the direction of Python is recognized, referring to him as Benevolent Dictator for Life (in English: Benevolent Dictator for Life, BDFL); However, on July 12, 2018, he declined from said position of honor without leaving a successor or successor and with a high-sounding statement:

So what are you all gonna do? To create a democracy? Anarchy? A dictatorship?
Guido van Rossum

On February 20, 1991, van Rossum first published the code on alt.sources, with version number 0.9.0. Classes with inheritance, exception handling, functions, and functions were already present at this stage of development. and modular types, such as: str, list, dict, among others. Also in this initial release appeared a module system adopted from Modula-3; van Rossum describes the module as "one of the largest units of Python programming". The exception model in Python is similar to that of Modula-3, with the addition of an else clause. In 1994, comp.lang.python, the main Python discussion forum, was formed, marking a milestone in the growth of the group of users of this language.

Python reached version 1.0 in January 1994. A feature of this release were functional programming tools: lambda, reduce, filter and map. Van Rossum explained that "12 years ago, Python acquired lambda, reduce(), filter() and map(), courtesy of Amrit Perm, a Lisp hacker who implemented because he missed them."

The last version released from CWI was Python 1.2. In 1995, van Rossum continued his work on Python at the Corporation for National Research Initiatives (CNRI) in Reston, Virginia, where he released several versions of the software.

While at CNRI, van Rossum launched the Computer Programming for Everybody (CP4E) initiative, aiming to make programming more accessible to more people, with a level of ' literacy' basic programming languages, similar to basic English literacy and math skills needed by many workers. Python played a crucial role in this process: due to its orientation towards clean syntax, it was already suitable, and the goals of CP4E bore similarities to its predecessor, ABC. The project was sponsored by DARPA. As of 2007, the CP4E project is dormant, and while Python tries to be easy to learn and not too arcane in its syntax and semantics, reaching non-programmers, it is not an active concern.

In the year 2000, the core team of Python developers moved to BeOpen.com to form the BeOpen PythonLabs team. CNRI requested that version 1.6 be made public, continuing its development until the development team left CNRI; its release schedule and that of version 2.0 had a significant amount of overlap. Python 2.0 was the first and only BeOpen.com release. After Python 2.0 was published by BeOpen.com, Guido van Rossum and the other developers from PythonLabs joined Digital Creations.

Python 2.0 borrowed a major feature from the Haskell functional programming language: list comprehensions. Python's syntax for this construct is very similar to Haskell's, except for Haskell's preference for punctuation characters, and Python's preference for alphabetic keywords. Python 2.0 also introduced a garbage collection system capable of collecting cyclic references.

Following this double release, and after van Rossum left CNRI to work with commercial software developers, it became clear that the option of using Python with software available under the GNU GPL was highly desirable. The license used at the time, the Python License, included a clause stipulating that the license was governed by the state of Virginia, which, in the view of the Free Software Foundation (FSF) lawyers, made it incompatible with the GPL. For versions 1.61 and 2.1, CNRI and FSF they made the Python license compatible with the GPL, renaming it the Python Software Foundation License. In 2001 van Rossum was awarded the FSF Award for the Advancement of Free Software.

Python code with syntax coloring

Python 2.1 was a derivative work of versions 1.6.1 and 2.0. It is from this moment that the Python Software Foundation (PSF) becomes the owner of the project, organized as a non-profit organization founded in 2001, modeled after the Apache Software Foundation. Included in this release was an implementation of scoping most similar to static scoping rules (of which Scheme is the originator).

A major innovation in Python 2.2 was the unification of Python types (types written in C), and classes (types written in Python) into a hierarchy. That unification achieved a pure and consistent Python object model. Generators that were inspired by the Icon language were also added.

Additions to the Python standard library and syntactic decisions were heavily influenced by Java in some cases: the logging package, introduced in version 2.3, is based on log4j; the SAX parser, introduced in 2.0; the threading package, whose class Thread exposes a subset of the interface of the class of the same name in Java.

Python 2, i.e. Python 2.7.x, was officially deprecated on January 1, 2020 (first planned for 2015) after which no security patches and other enhancements will be released for it. With the end of the Python 2 lifecycle, only the Python 3.6.x branch and later are supported.

Today, Python is applied in the fields of artificial intelligence and machine learning.

Characteristics and paradigms

Python is a multi-paradigm programming language. This means that rather than forcing programmers to adopt a particular style of programming, it allows for several styles: object-oriented programming, imperative programming, and functional programming. Other paradigms are supported through the use of extensions.

Python uses dynamic typing and reference counting for memory management.

An important feature of Python is dynamic name resolution; that is, what binds a method and a variable name during program execution (also called dynamic method binding).

Another goal of language design is ease of extension. New modules can be easily written in C or C++. Python can be included in applications that need a programmable interface.

Although Python programming could be considered hostile to traditional Lisp functional programming in some situations, there are many analogies between Python and minimalist languages in the Lisp family such as Scheme.

Philosophy

Python users often refer to the Python philosophy which is quite analogous to the Unix philosophy. Code that follows the principles of Python is said to be "pythonic". These principles were described by Python developer Tim Peters in The Zen of Python

  • Beautiful is better than ugly.
  • Explicit is better than implied.
  • Simple is better than complex.
  • Complex is better than complicated.
  • Plano is better than nesting.
  • Spread is better than dense.
  • Legibility counts.
  • Special cases are not as special as breaking the rules.
  • The practical wins the pure.
  • Mistakes should never be left silently.
  • Unless they've been explicitly silenced.
  • Faced with ambiguity, he rejects the temptation to guess.
  • There should be one — and preferably just one — obvious way to do it.
  • Although that way may not be obvious at first unless you are Dutch.
  • Now it's better than ever.
  • Although Never. is often better than Right now..
  • If implementation is hard to explain, it's a bad idea.
  • If implementation is easy to explain, it may be a good idea.
  • The spaces of names (namespaces) are a great idea Let's do more of those things!
Tim Peters, Python Zen

Since version 2.1.2, Python includes these dots as an easter egg that is displayed when import this is executed.

LAMP comprises Python (here with Squid)

Interactive mode

The standard Python interpreter includes an interactive mode in which instructions are written in a kind of command interpreter: expressions can be entered one by one, and the result of their evaluation can be seen immediately, which gives the possibility to test portions of code in interactive mode before integrating it as part of a program. This is useful both for people just getting familiar with the language and for more advanced programmers.

There are other programs, such as IDLE, bpython or IPython, which add extra functionality to the interactive mode, such as automatic code completion and language syntax coloring.

Example of interactive mode:

oriented 1 + 12oriented a = Range(10)oriented print(list(a)[chuckles]0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Language elements and syntax

Python is meant to be an easy-to-read language. Its format is visually neat and often uses English keywords where other languages use punctuation. Unlike many other languages, it does not use square brackets to delimit blocks, and semicolons are allowed after declarations, but are rarely, if ever, used. It has fewer syntactic exceptions and special cases than C or Pascal.

Designed to be easily read, one of its characteristics is the use of words where other languages would use symbols. For example, the logical operators !, ||, and && in Python are written not, or and and, respectively. Curiously, the Pascal language is, together with COBOL, one of the languages with very clear syntax and both are from the 70s. The idea of clear and readable code is not something new.

The content of code blocks (loops, functions, classes, etc.) is delimited by spaces or tabs, known as indentation, before each command line belonging to the block. Python thus differs from other scripting languages. programming that maintains the custom of declaring blocks using a set of characters, usually enclosed in braces {}. Both spaces and tabs can be used to indent the code, but it is recommended not to mix them.

Factorial function in C (optional bleeding) Factorial function in Python (mandatory bleeding)
int factorial(int x){ if (x . 0 日本語 x % 1 = 0) { printf("x must be an integer greater or equal to 0"); return -1; //Error ! if (x  0) { return 1; ! return x  factorial(x - 1);!
def factorial(x(c): assert x  0 and x % 1  0, "x must be an integer greater or equal to 0." if x  0: return 1 else: return x  factorial(x - 1)

Due to the syntactic significance of indentation, each statement must be contained on a single line. However, if for readability you want to divide the instruction into several lines, adding a backslash at the end of a line indicates that the instruction continues on the next.

These instructions are equivalent:

 List=[chuckles]'value 1','value 2','value 3'] chain='This is a pretty long chain'
 List=[chuckles]'value 1','value 2' 
 ,'value 3'] chain='This is a string' 
 'Long bass'

Comments

You can put comments in two ways. The first and most appropriate for long comments is using the notation ''' comment ''', three opening and three closing apostrophes. The second notation uses the # symbol, and they extend to the end of the line.

The interpreter ignores comments, which is useful if you want to put additional information in your code. For example, an explanation about the behavior of a section of the program.

''Longer comment on a line in Python''print("Hello world") # It is also possible to add a comment at the end of a code line

Variables

Variables are dynamically defined, which means that you don't have to specify their type beforehand, and they can take on different values at another time, even of a different type than the one they had. previously. The symbol = is used to assign values.

x = 1x = "text" # This is possible because the types are dynamically assigned

Variable names can contain numbers and letters but must begin with a letter, and there are 28 reserved words:

  • and
  • assert
  • break
  • class
  • continue
  • def
  • del
  • elif
  • else
  • except
  • exec
  • finally
  • for
  • from
  • global
  • if
  • import
  • in
  • is
  • lambda
  • not
  • or
  • pass
  • print
  • raise
  • return
  • try
  • while

Data Types

Python 3. The standard type hierarchy.png

The data types can be summarized in this table:

Type Class Notes Example
strChain Unchangeable 'Cadena'
unicodeChain Unicode Version stru'Cadena'
listSequence Mutable, can contain objects of various types [4.0, 'Cadena', True]
tupleSequence Unchangeable, can contain objects of various types (4.0, 'Cadena', True)
setSet Mutable, without order, does not contain duplicates {4.0, 'Cadena', True}
frozensetSet Unchangeable, without order, does not contain duplicates frozenset([4.0, 'Cadena', True])
dictMapping Key pair group: value {'key1': 1.0, 'key2': False}
intInteger number Fixed accuracy, converted long in case of overflow. 42
longInteger number Arbitrary precision 42L or 456966786151987643L
floatNumber of decimal Double-precision floating coma 3.1415927
complexComplex number Real part and imaginary part j. (4.5 + 3j)
boolBooleano True or false boolean value True o False
  • Mutable: if your content (or such value) can be changed in execution time.
  • Unchangeable: if your content (or such value) cannot be changed in execution time.

Conditionals

A conditional statement (if) executes its inner block of code only if a certain condition is met. It is defined using the if keyword followed by the condition, and the code block. If additional conditions exist, they are introduced using the elif keyword followed by the condition and its code block. Conditions are evaluated sequentially until the first one that is true is found, and its associated block of code is the only one that is executed. Optionally, there can be a final block (the else keyword followed by a code block) that is executed only when all of the above conditions were false.

oriented true = Trueoriented if true: # It is not necessary to put "true == True"... print("True")... else:... print("Falso")...Trueoriented language = Python.oriented if language  "C": # language is not "C", so this block will be ignored and evaluated the following condition... print("Schedule Language: C")... elif language  Python.: # You can add as many "elif" blocks as you want... print("Schedule Language: Python")... else: # In case none of the above conditions were true, this block would be executed... print("Schedule Language: Undefined")...Language of programming: Pythonoriented if true and language  Python.: # Using "and" to check that both conditions are true... print("Right and Programming Language: Python")...True and Language of programming: Python

For-loop

The for loop is similar to foreach in other languages. Loops through an iterable object, such as a list, tuple, or generator, and for each element of the iterable executes the inner code block. It is defined with the keyword for followed by a variable name, followed by in, followed by the iterable, and finally the inner code block. On each iteration, the next element of the iterable is assigned to the specified variable name:

oriented List = [chuckles]"a", "b", "c"]oriented for i in List: # We're on a list, which is iterable.... print(i)...abcoriented chain = "abcdef"oriented for i in chain: # Iteramos on a chain, which is also iterable... print(i, end=',') # Adding end=, 'in the end we do not introduce a line jump, but a comma and a space...a, b, c, d, e, f,

While-loop

The while loop evaluates a condition and, if true, executes the inner code block. Continue evaluating and executing as long as the condition is true. It is defined with the while keyword followed by the condition, and then the inner code block:

oriented Number = 0oriented while Number . 10:... print(Number, end=")... Number += 1 # A good programmer will modify the control variables at the end of the while cycle...0 1 2 3 4 5 6 7 8 9

Lists and Tuples

  • To declare a List used the brackets []instead, to declare a parenthesis used (). Both elements are separated by commas, and in the case of Tuplas you need to have at least one coma.
  • Both lists like Tuplas can contain elements of different types. Notwithstanding lists usually used for elements of the same type in variable quantity while the Tuplas are reserved for different elements in fixed amount.
  • To access the elements of a List or a whole index (starting for "0", not for "1") is used. Negative indexes can be used to access elements from the end.
  • The lists are characterised by being mutable, that is, you can change your content in execution time, while the Tuplas are immutable since it is not possible to modify the content once created.
Lists
oriented List = [chuckles]"abc", 42, 3.1415]oriented List[chuckles]0] # Access an element by its index'abc'oriented List[chuckles]-1] # Access an element using a negative index3.1415oriented List.append(True) # Add an item at the end of the listoriented List[chuckles]'abc', 42, 3.1415, True]oriented of List[chuckles]3] # Delete a list item using an index (in this case: True)oriented List[chuckles]0] = "xyz" # Re-assign the value of the first element of the listoriented List[chuckles]0:2] # Show the elements of the "0" index list to "2" (not including the latter)[chuckles]'xyz', 42]oriented List_anidada = [chuckles]List, [chuckles]True, 42L]] # It is possible to nest listsoriented List_anidada['xyz', 42, 3.1415], [chuckles]True, 42L]]oriented List_anidada[chuckles]1][0] # Access an element from a list within another list (from the second element, show the first element)True
Tuplas
oriented  = ("abc", 42, 3.1415)oriented [chuckles]0] # Access an element by its index'abc'oriented of [chuckles]0] # It is not possible to delete (or add) an element in a tuple, which will cause an exception( Exception )oriented [chuckles]0] = "xyz" # Nor is it possible to re-assign the value of an element in a tuple, which will also cause an exception( Exception )oriented [chuckles]0:2] # Show the tuple elements of the "0" index to "2" (not including the latter)('abc', 42)oriented tupla_anidada = (, (True, 3.1415) # It is also possible to nest tuplasoriented 1, 2, 3, "abc" # This is also a tuple, although it is advisable to put it in parentheses (remember that requires at least one comma)(1, 2, 3, 'abc')oriented (1) # Although in parentheses, this is not a tuple, since it does not have at least one comma, so only the value will appear1oriented (1(,) # Instead, in this other case, it's a tupper.(1(,)oriented (1, 2) # With more than one element is not necessary the final comma(1, 2)oriented (1, 2(,) # Although adding it does not modify the result(1, 2)

Dictionaries

  • To declare a dictionary keys are used {}. They contain elements separated by commas, where each element is formed by a pair clave:valor (the symbol : separates the key from its corresponding value).
  • Them dictionaries are mutable, that is, you can change the content of a valor in execution time.
  • Instead, the claves of a dictionary They must be immutable. This means, for example, that we cannot use or use lists and dictionaries Like claves.
  • The valor associated with a clave can be of any type of dataeven a dictionary.
oriented dictionary = {"chain": "abc", "number": 42, "list": [chuckles]True, 42L] # Dictionary that has different values for each key, even a listoriented dictionary[chuckles]"chain"] # Using a key, you access its value'abc'oriented dictionary[chuckles]"list"][0] # Access a list element within a value (of the value of the "list" key, show the first element)Trueoriented dictionary[chuckles]"chain"] = "xyz" # Re-assign the value of a keyoriented dictionary[chuckles]"chain"]'xyz'oriented dictionary[chuckles]"decimal"] = 3.1415927 # Insert a new key element: valueoriented dictionary[chuckles]"decimal"]3.1415927oriented dictionary_mixto = {"tupla": (True, 3.1415), "dictionary": dictionary! # It is also possible that a value is a dictionaryoriented dictionary_mixto[chuckles]"dictionary"]["list"][1] # Access an element within a list, which is within a dictionary42Loriented dictionary = {"abc",): 42! # If it is possible that a key is a tuple, because it is unchangeableoriented dictionary = "abc"]: 42! # It is not possible that a key is a list, since it is mutable, which will cause an exception( Exception )

Switch Case Statement

Python has the switch-case structure since version 3.10. This is called Structural Pattern Matching.

match variable:case condition:# I codecase condition:# I codecase condition:# I codecase _:# I code

It should be noted that this functionality is considerably more complex than the known switch-case of most languages, since it not only allows you to perform a comparison of the value, but you can also check the type of the object, and its attributes. In addition, you can also perform direct unpacking of data streams, and check them specifically.

The following example checks the attributes of our Point instance. If these are not equal to x10 and y40, it will go to the next condition.

It is important to note that Point(x=10, y=40) is not constructing a new object, although it may appear to be.

from dataclasses import dataclass@dataclassclass Period:x: intand: intCoordinated = Period(10, 34)match Coordinated:case Period(x=10, and=40(c): # the attributes "x" and "y" have the specific valueprint("Coordinated 10, 40")case Period(): # if it's a point instanceprint("it's a point")case _: # no condition fulfilled (default)print("It's not a point")

In earlier versions, there are different ways to perform this logical operation in a similar way:

Using if, elif, else

We can use the structure as follows:

oriented if condition1:... do1oriented elif condition2:... make2oriented elif Condition3:... do3oriented else:... make

In this structure it will be executed by controlling condition1, if it is not fulfilled it will go to the next one and so on until it enters the else. A practical example would be:

oriented def calculus(op,a,b(c):... if 'sum'  op:... return a + b... elif 'rest'  op:... return a - b... elif 'mult'  op:... return a  b... elif 'div'  op:... return a/b... else:... return Noneorientedoriented print(calculus('sum',3,4)7

We could say that the negative side of the statement armed with if, elif and else is that if the list of possible operations is very long, it has to go through them one by one until reaching the correct one.

Using dictionary

We can use a dictionary for the same example:

oriented def calculus(op,a,b(c):... return {... 'sum': lambda: a + b,... 'rest': lambda: a - b,... 'mult': lambda: a  b,... 'div': lambda: a/b... !.get(op, lambda: None)()orientedoriented print(calculus('sum',3,4)7

This way, if the options were many, it wouldn't loop through all of them; it would just go directly to the operation looked for in the last line .get(op, lambda: None)() we are giving the default option.

Sets

  • Them joints are built through set(items) where items is any object iterableLike, lists or Tuplas. Them joints they do not maintain the order or contain duplicate elements.
  • They are usually used to remove duplicates from a sequence, or for mathematical operations such as intersection, union, difference and symmetrical difference.
oriented interchangeable = frozen(b)"a", "b", "a"]) # A list is used as an iterable objectoriented interchangeablefrozen(b)'a', 'b'])oriented group1 = set(b)"a", "b", "a"]) # First piece of furnitureoriented group1set(b)'a', 'b'])oriented joint = set(b)"a", "b", "c", "d"]) # Second piece of furnitureoriented jointset(b)'a', 'c', 'b', 'd']) # Remember, they don't keep order, like dictionaries.oriented group1 " joint # Intersectionset(b)'a', 'b'])oriented group1 日本語 joint # Unionset(b)'a', 'c', 'b', 'd'])oriented group1 - joint # Difference (1)set([])oriented joint - group1 # Difference (2)set(b)'c', 'd'])oriented group1 ^ joint # Symmetrical differenceset(b)'c', 'd'])

List comprehensions

A list comprehension is a compact expression for defining lists. Like lambda, it appears in functional languages. Examples:

oriented Range(5) # The "range" function returns a list, starting at 0 and ending with the indicated number minus one[chuckles]0, 1, 2, 3, 4]oriented [chuckles]ii for i in Range(5)] # For each element of the range, it multiplies by itself and adds it to the result[chuckles]0, 1, 4, 9, 16]oriented List = [i, i + 2) for i in Range(5)]oriented List[0, 2), (1, 3), (2, 4), (3, 5), (4, 6)]

Functions

  • The functions defined with the keyword deffollowed by the name of the function and its parameters. Another way to write functions, although less used, is with the keyword lambda (which appears in functional languages like Lisp).
  • The returned value in the functions with def will be given with the instruction return.
  • The functions defined with def can receive special parameters to handle excess arguments.
    • The parameter *args receives as a tupla a variable number of positional arguments.
    • The parameter **kwargs receives as a dictionary a variable number of arguments by keywords.

def:

oriented def amount(x, and=2(c):... return x + and # Return the sum of the value of the variable "x" and the value of "y"...oriented amount(4) # The variable "y" is not modified, being its value: 26oriented amount(4, 10) # The variable "y" does change, being its new value: 1014

*args:

oriented def amount(args(c):... result = 0... # It would be the tupla of arguments... for num in args:... result += num # adds all the arguments... return result # returns the result of the sum...orientedamount(2,4)6orientedamount(1,3,5,7,9) # Doesn't matter the number of positional variables that pass to the function25

**kwargs:

def amount(**kwargs(c):... result = 0... # it was the dictionary of arguments... for key, value in kwargs.items():... result += value # adds all the values of the arguments... return result...orientedamount(x=1, and=3)4orientedamount(x=2, and=4, z=6) # doesn't matter the number of variables per key that pass to the function12

lambda:

oriented amount = lambda x, and=2: x + andoriented amount(4) # The variable "y" is not modified, being its value: 26oriented amount(4, 10) # The variable "y" does change, being its new value: 1014

Classes

  • The classes defined with the keyword classfollowed by the name of the class and, if he inherits from another classThe name of this one.
  • In Python 2.x it was advisable for a class to inherit from "Object", in Python 3.x it is no longer necessary.
  • In one class a "method" equals a "function", and a "attribute" equals a "variable".
  • "__init__" is a special method that is executed at the time of class, is usually used to initialize attributes and execute necessary methods. Like all methods in Python, you must have at least one parameter, it is usually used self. The other parameters will be the ones indicated at the instance of the class.
  • Attributes that are desired to be accessible from outside class must be declared using self. in front of the name.
  • In Python there is no concept of encapsulation, so the programmer must be responsible for assigning the values to the attributes
oriented class Person():... def __init__(self, Name, Age(c):... self.Name = Name # Any attribute... self.Age = Age # Another attribute any... def show_age(self(c): # You need to at least have a parameter, usually: "self"... print(self.Age) # showing a attribute... def modify_(self, Age(c): # Modifying Age... if Age . 0 or Age  150: # It is verified that the age is not less than 0 (something impossible), nor greater than 150 (something really difficult)... return False... else: # If it is in the 0-150 range, then the variable is modified... self.Age = Age # Age change...oriented p = Person('Alicia', 20) # Installing the class, as you can see, does not specify the value of "self"oriented p.Name # The "name" variable of the object is accessible from outside'Alicia'oriented p.Name = 'Andrea' # And therefore, you can change your contentoriented p.Name'Andrea'oriented p.show_age() # It's called a class method.20oriented p.modify_(21) # It is possible to change the age using the specific method we have done to do so in a controlled wayoriented p.show_age()21

Modules

There are many properties that can be added to the language by importing modules, which are "minicodes" (mostly also written in Python) that provide certain functions and classes to perform certain tasks. An example is the Tkinter module, which allows you to create graphical interfaces based on the Tk library. Another example is the os module, which provides access to many operating system functions. Modules are added to codes by typing import followed by the name of the module we want to use.

Installing modules (pip)

Installing modules in Python can be done using the software tool (usually included with Python installations) Pip. This tool allows the management of the different packages or installable modules for Python, thus including the following characteristics:

  • Package installation.
    • Installation of specific versions of packages.
    • Installation from a configuration file.
  • Uninstallation.
  • Update.

Interface to the operating system

The os module provides functions to interact with the operating system:

oriented import os # Module providing operating system functionsoriented os.name # Returns the name of the operating system'posix'oriented os.mkdir("/tmp/example") # Create a directory on the specified routeoriented import time # Module for working with dates and hoursoriented time.strftime("%y-%m-%d %H:%M:%S") # Giving it a certain format, returns the date and/or current time'2010-08-10 18:01:17'

For file management tasks, the shutil module provides a higher-level interface:

oriented import shutiloriented shutil.copyfile('datos.db', 'information.db')'information.db'oriented shutil.Move.('/build/programs', 'dir_progs')'dir_progs'

File wildcards

The glob module provides a function for creating lists of files from wildcard folder searches:

oriented import globoriented glob.glob('*.py')[chuckles]'numeros.py', 'exemplo.py', 'exemplo2.py']

Command line arguments

Command line arguments are stored in the argv attribute of the sys module as a list.

oriented import sysoriented print(sys.argv)[chuckles]'demonstration.py', 'One', 'two', 'three']

Math

The math module allows access to floating-point math functions:

oriented import Mathoriented Math.#(Math.piss / 3)0,494888338963oriented Math.log(1024, 2)10.0

The random module is used to perform random selections:

oriented import randomoriented random.choice(b)'durazno', 'manzana', 'frutilla'])'durazno'oriented random.sample(Range(100), 10) # choice without replacement[chuckles]30, 23, 17, 24, 8, 81, 41, 80, 28, 13]oriented random.random() # A float at random0.23370387692726126oriented random.randrange(6) # A random integer taken from range(6)3

The statistics module is used for basic statistics, for example: mean, median, variance, etc.:

oriented import statisticsoriented data = [chuckles]1.75, 2.75, 1.25, 0.5, 0.25, 1.25, 3.5]oriented statistics.mean(data)1.6071428571428572oriented statistics.average(data)1.25oriented statistics.variance(data)1.3720238095238095

Dates and Times

The datetime module allows you to handle dates and times:

oriented from datetime import dateoriented today = date.today()oriented todaydatetime.date(2017, 8, 16)

Turtle Module

The turtle module allows the implementation of turtle graphs:

oriented import turtleoriented turtle.Think(2)oriented turtle.left(120)oriented turtle.forward(100)

Object system

In Python everything is an object (even classes). Classes, being objects, are instances of a metaclass. Python also supports multiple inheritance and polymorphism.

oriented chain = "abc" # A chain is an object of "str"oriented chain.upper() # Being an object, it possesses its own methods'ABC'oriented List = [chuckles]True, 3.1415] # A list is an object of "list"oriented List.append(42L) # A list also (like everything) is an object, and also has its own methodsoriented List[chuckles]True, 3.1415, 42L]

Standard Library

Python comes with "including legs"

Python has a large standard library, used for a variety of tasks. This comes from the "batteries included" ("batteries included") referring to Python modules. Modules from the standard library can be enhanced by custom modules written in both C and Python. Due to the great variety of tools included in the standard library, combined with the ability to use low-level languages such as C and C++, which are capable of interfacing with other libraries, Python is a language that combines its clear syntax with the immense power of less elegant languages.

Implementations

There are various implementations of the language:

  • CPython is the original implementation, available for several platforms on the official Python site.
  • IronPython is the implementation for.NET
  • Stackless Python is the CPython variant that tries not to use the stack C (www.stackless.com)
  • Jython is the implementation made in Java
  • Pippy is the implementation for Palm (pippy.sourceforge.net)
  • PyPy is a Python implementation written in Python and optimized by JIT (pypy.org)
  • ActivePython is a proprietary implementation of Python with extensions, for production servers and critical mission applications developed by ActiveState Software.

Incidents

Throughout its history, Python has presented a series of incidents, of which the most important have been the following:

  • On 13 February 2009, a new version of Python was launched under the key name Python 3000. o, abbreviated, "Py3K". This new version includes a whole series of changes that require rewriting the previous version code. To facilitate this process along with Python 3, an automatic tool called 2to3.
  • In the Windows 10 operating system, from its May 2019 update, it has the Python language assisted pre-installation feature and several of its additional tools.

Contenido relacionado

Redundancy bit

The redundancy bit is a bit that is sometimes deliberately introduced into the transmission or recording of information without being part of it, but that...

Simple Network Management Protocol

The Simple Network Management Protocol or SNMP is a An application layer protocol that facilitates the exchange of management information between network...

Bailey-Borwein-Plouffe formula

The Bailey-Borwein-Plouffe formula allows us to calculate the nth digit of π in base 2 without having to find the precedents, quickly and using very little...
Más resultados...
Tamaño del texto:
Copiar