Video Python syntax and semantics
Design philosophy
Python is designed to be a very readable language. It has a relatively uncluttered visual layout and often uses English keywords where other languages ââuse punctuation. Python aims to be simple and consistent in its syntax design, packed in a mantra "There must be one - and preferably only one - the obvious way to do it", from "The Zen of Python".
This spell deliberately opposes the Perl and Ruby spells, "there's more than one way to do it".
Maps Python syntax and semantics
Keyword
Python has the following keywords or words protected by law ; they can not be used as identifiers.
- Notes
Indent
Python uses white space to restrict the control flow block (following the off-side rule). Python borrows this feature from its predecessor ABC: instead of punctuation or keywords, it uses an indent to show the path of the block.
In the so-called "free format" language - which uses a block structure derived from ALGOL - the code block is set with brackets ( {}
) or keywords. In most coding conventions for these languages, programmers conventionally insert code in a block, to visually differentiate it from the surrounding code (prettyprinting).
Consider the function, foo
, passed one parameter, x
, and if the parameter 0 will call bar
and baz
, otherwise it will call qux
, forward x
, and also call itself recursively, passing x-1
as a parameter. Here is an implementation of this function in C and Python:
foo
works in Python:
Python mandates the convention that programmers in ALGOL style languages ââoften follow. Incorrect indentation codes can be understood by human readers differently than compilers or interpreters.
This example illustrates an indentation error with Python:
Here, unlike the above example Python foo
, the call function foo (x - 1)
is always executed, resulting in an endless recursion. Such indentation errors (such as accidental unintentional deletion of the last line) are possible only in programming languages ââthat do not mark blocks with distinct markers, such as curly braces in C. In this particular case, even editors with automatic indentations can prevent misbehavior from this Python code. These unwanted errors can easily break into the codebase without prior notification by the programmer. In most other programming languages, this is not possible (removing block-end markers in C will lead to compiler errors), and this makes Python syntax less powerful than most other languages.
The space character and tab character are currently accepted as indented form in Python. Since many tools do not distinguish them visually, mixing spaces and tabs can create bugs that make a special effort to find (lasting suggestions among Python users have removed the tabs as block markers; other Python users instead recommend removing spaces). In addition, formatting routines that remove whitespaces - for example, many Internet forums - can destroy Python program syntax, whereas programs in parentheses will only become more difficult to read.
Many popular code editors handle the Python indentation convention seamlessly, sometimes after the configuration option is enabled.
Data Structure â ⬠<â â¬
Since Python is a dynamically typed language, Python values ââ, are not variables, carry types. This has implications for many aspects of the way language functions.
All variables in Python hold a reference to the object, and this reference is passed to the function; function can not change the variable reference value in its call function ( is not completely correct, see below ). Some people (including Guido van Rossum himself) have called this parameter-passing scheme "Call by object reference." Reference object means name, and the forwarded reference is "alias", ie copy of the reference to the same object, as in C/C. The value of an object can be changed in a function called "alias", for example:
The "myfunc" function changes the value of "alist" with the formal argument "al", which is the alias of "alist". However, any attempt to operate on the alias itself will have no effect on the original object. In Python, the names that are not accessible-globally and not-declared-are all aliases.
Among languages ââthat are dynamically typed, Python is sufficiently checked. Implicit conversions are defined for numeric types (as well as booleans), so one can legitimately multiply complex numbers with long integers (for example) without explicit casting. However, there is no implicit conversion between (eg) numbers and strings; string is an invalid argument for a mathematical function that expects a number.
Basic type
Python has various basic data types. Along with conventional integers and floating-point arithmetic, it transparently supports arbitrary precision arithmetic, complex numbers, and decimal point numbers.
Python supports various string operations. Strings in Python can not be changed, so string operations such as character substitution, which in other programming languages ââmight change the string in place, returns a new string in Python. Performance considerations are sometimes encouraged to use special techniques in programs that modify strings intensively, such as combining character arrays into strings only when needed.
Type of collection
One very useful aspect of Python is the concept of type collection (or container ). Generally collections are objects that contain other objects in a way that is easily referenced or indexed . Collections come in two basic forms: sequence and mapping .
The sequence type is a list (dynamic array), tuples, and strings. All sequences are positional indexed (0 to long - 1) and all but strings can contain any type of object, including several types in the same order. Both the string and the tuple can not be changed, making it the perfect candidate for the dictionary key (see below). The list, on the other hand, may change; elements can be inserted, deleted, modified, added, or sorted in place.
Mapping, on the other hand, is an un-ordered type that is implemented in the form of a dictionary that "maps" a set of keys that do not change to the appropriate element (such as math functions). For example, one can define a dictionary that has the string "toast"
mapped to integer 42 or vice versa. The keys in the dictionary must be of an unchanged Python type, such as an integer or string, because under the hood they are implemented through a hash function. This makes the search time faster, but requires the key does not change (and also leads to a lack of dictionary sequence).
Dictionaries are also important for the internal language because they are at the core of all Python objects and classes: mapping between variable names (strings) and values ââthat reference names are stored as dictionaries (see Object system). Because this dictionary can be accessed directly (via the object attribute __ dict __
), metaprogramming is a direct and natural process in Python.
A set of set types is added to the core language in version 2.4. One set is an unordereded, non-duplicate collection, and implements theoretical set operations such as union, intersection, difference, symmetric difference, and subset testing. There are two types of sets: set
and frozenset
, the only difference is that set
can change and frozenset
is eternal. Elements in a set must be able to be hashed and immutable. So, for example, frozenset
can be an element of ordinary set
whereas the reverse is not true.
Python also provides the ability to manipulate extensive collections such as those built in the containment check and generic iteration protocols.
System object
In Python, everything is an object, even a class. Classes, as objects, have classes, known as their metaclasses. Python also supports multiple inheritance and mixins.
Language supports extensive introspection of types and classes. Kind of readable and comparable - type is an example type
. The attribute of an object can be extracted as a dictionary.
Operators can be overloaded in Python by defining special member functions - for example, defining __ add __
in a class allows one to use the
operator of the class member.
Literal
String
Python memiliki berbagai jenis string literal.
Literal string normal
Single or double quotes can be used to quote strings. Unlike in Unix shell languages, Perl or Perl-influenced languages ââlike Ruby or Groovy, single quotes and double quotation marks are identical, ie there is no interpolation of the expression string $ foo . However, interpolation can be done in various ways: with the string-format operator % , using the "format" method or with "f-string" (since Python 3.6).
For example, the Perl statement:
equivalent to one of these Python statements:
Literal multi-line string
There are also multi-line strings, which begin and end with a series of three single or double quotes and work like here documents in Perl and Ruby.
A simple example with variable interpolation (using string-format operator % ) is:
String raw
Finally, all of the previously mentioned string types come in "raw" varieties (denoted by placing the literal r before the opening quote), which do not backslash-interpolate and are therefore very useful for regular expressions; compare "@ -quoting" in C #. The raw string initially includes special for regular expressions. Due to the limitations of the tokenizer, the raw string may not have a backslash behind. Creating a raw string that holds a Windows path that ends with a backslash requires some variation of a solution (typically, using forward slashes instead of backslashes, since Windows accepts both).
Examples include:
Combine literal adjacent strings
Literal strings (using different citation conventions) appear adjacent and separated only by spaces (including newlines), which are allowed and collected into longer strings. Thereby
setara dengan
Numbers
The numerical literal in Python is the normal type, ie. 0
, -1
, 3.4
, 3.5e-8
.
Python has random integers and automatically increases the required storage size. Prior to Python version 3, there were two types of integral numbers: traditional fixed-size integers and "long" integers of random ranges. Conversion to "length" integers is done automatically when needed, and thus programmers usually do not have to be aware of two integral types. In newer language versions, fixed-size integers are completely lost.
Python supports normal floating point numbers, which are created when a point is used literally (eg 1.1
), when an integer and floating point number are used in an expression, or as a result of some mathematical operations ("division is true "via operator /
, or exponential with a negative exponent).
Python also supports complex numbers natively. Complex numbers are indicated by J or j
suffixes, e.g. 3 4j
. List, tuple, set, dictionary
Python has syntactic support for the creation of container types.
List (class list
) is the order of items that vary from arbitrary type, and can be created with special syntax
or use normal object creation
Tuples (class tuple
) are the order of items that vary from arbitrary type. There is also a special syntax for creating tuples
Although tuples are created by separating items with commas, the overall construction is usually wrapped in parentheses to improve readability. Empty tuples are denoted by ()
.
Set (class set
) is a mutable container of an arbitrary type, without duplicates. Item not ordered, but set iteration support for the item. The syntax for the creation set appears in Python 2.7/3.0
In previous Python versions, sets will be created by initializing the set class with the list argument. Python sets are very similar to mathematical sets, and support operations such as setting up intersections and pooling.
Python also comes with the frozenset
class for sets that can not be changed.
Dictionary (class dict
) is a mutable mapping that binds the associated key and value. Python has a special syntax for creating dictionaries ( {key: value}
)
The dictionary syntax is similar to the set syntax, the difference being the presence of a colon. Empty literal {}
produces an empty dictionary instead of an empty set, which is instead created using a non-literal constructor: set ()
.
Operator
Arithmetic
Python includes
, -
, *
, /
, %
(modulus), and operator **
(exponentiation), with the usual mathematical precedents they use.
Traditionally, x/y
does the integer division if both x
and y
are integers (returns the result base), and returns the buoy if whether it's a float. However, since Python is a dynamically typed language, it is not always possible to know which operations are being performed, which often cause subtle bugs. For example, with
Calls for mean ([3.0, 4.0])
will return 3.5, but mean ([3, 4])
will return 3. If this is not the intended behavior, using a solution like
To avoid this problem, a proposal was made to change the behavior of Python division operators. In Python 2.2, the new operator //
is introduced for the floor division, both for both integer and floating-point arguments. The /
operator is changed so that the results for two integers returns the buoy, but for backwards compatibility, this behavior must be explicitly requested until Python 3.0.
Operators comparison
Basic benchmarking operators like ==
, & lt;
, & gt; =
, and so on are used for all sorts of values. Numbers, strings, sequences, and mappings can all be compared. Although different types (such as str
and int
) are defined to have consistent relative sequences, this is considered a historical design game and will no longer be allowed in Python 3.0.
Chained comparison expressions like a & lt; b & lt; c
has approximately the meanings they have in mathematics, rather than the unusual meanings found in C and similar languages. Terms are evaluated and compared sequentially. This operation has a short circuit semantics, which means that evaluation is guaranteed to stop as soon as the verdict is clear: if a & lt; b
is incorrect, c
is never evaluated because the expression can not be true anymore.
For expression with no side effects, a & lt; b & lt; c
is equivalent to a & lt; b and b & lt; c
. However, there is a substantial difference when the expression has side effects. a & lt; f (x) & lt; b
will evaluate f (x)
exactly once, while a & lt; f (x) and f (x) & lt; b
will evaluate it twice if the value a
is less than f (x)
and one time instead.
Logic operator
Python 2.2 and earlier did not have explicit boolean types. In all Python versions, the boolean operator treats zero or blank values ââlike ""
, 0
, None
, 0.0
, []
, and {}
as false, while generally treating non-empty values ââinstead of zero as true. In Python 2.2.1, boolean constants True
and False
are added to the language (subclasses of 1 and 0). Binary comparison operators like ==
and & gt;
returns True
or False
.
Boolean operators and
and or
use minimal evaluation. For example, y == 0 or x/y & gt; 100
will never raise the divide-by-zero exception. These operators return the last evaluated operand value instead of True
or False
. Thus the expression (4 and 5)
evaluates to 5
, and (4 or 5)
evaluates to 4
.
Functional programming
As mentioned above, another Python strength is the availability of functional programming styles. As expected, this makes working with lists and other collections much easier.
Comprehensions
One such construction is the list comprehension, which can be expressed in the following format:
Using a list comprehension to calculate the first five powers of two:
The Quicksort algorithm can be expressed elegantly (albeit inefficiently) using an understanding list:
Python 2.7 also supports sets of comprehensions and dictionary comprehensions.
First-class functions
In Python, a function is a first class object that can be created and distributed dynamically.
Python's limited support for anonymous functions is the lambda
construct. An example is an anonymous function that packs its inputs, called argument 5:
Lambdas are limited to contain expressions rather than statements, although control flows can still be implemented less elegantly in lambda by using short circuits, and are more idiomatic with conditional expressions.
Closure
Python has supported the lexical closure since version 2.2. Here's an example:
Python syntax, though, sometimes causes other language programmers to think that closing is not supported. The scope of variables in Python is implicitly determined by the scope in which one assigns a value to a variable, unless the scope is explicitly stated with global
or nonlocal
.
Note that the binding of closing a name to a value can not be changed from within a function. Given:
and you can see that b
, which is visible from the scope of the closure, retains the value it holds; the changed binding of b
inside the inner function does not spread. The way around this is to use the nonlocal b
statement in the bar
. In Python 2 (which does not have nonlocal
), a commonly used solution is to use values ââthat can change and change that value, not binding it. For example, list with one element.
Generator
Introduced in Python 2.2 as an optional feature and completed in version 2.3, the generator is a Python mechanism for lazy evaluation of a function that would otherwise return an intensive list of space-computing or computing inhibitors.
This is an example to lazily generating primes:
To use this function, simply call, for example:
The generator definition looks identical to the function, except the generate
keyword is used instead of return
. However, the generator is an object with persistent status, which can repeatedly enter and leave the same scope. A generator call can then be used instead of a list, or another structure whose elements will be repeated. Each time the for
loop in the instance requires the next item, the generator is called, and generates the next item.
Generator does not have to be unlimited like the example of prime number above. When the generator expires, an internal exception is generated that shows up to any call context that has no more value. Loop for
or other iterations will end.
Generator Expression
Introduced in Python 2.4, the generator expression is a lazy evaluation equivalent to an understanding list. Using the prime generator provided at the top, we might define a lazy collection, but not infinite enough.
Most of the memory and time required to generate many of these primes will not be used until the required element is actually accessed. Unfortunately, you can not do simple indexing and generator slicing, but must use your i-itertools or loop "play module". Instead, the list comprehension is functionally equivalent, but
The understanding list will soon make a huge list (with 78498 items, in the example, but temporarily create a list of primes under two million), even if most elements are never accessed. Understanding the generator is more parsimony.
Dictionary and set comprehensions
While the list and the generator have an understanding/expression, in older versions of Python than the other 2.7 types of Python built-in collections (dicts and sets) must be enclosed in using a list or generator:
Python 2.7 and 3.0 bring together all types of collections by introducing dict and set comprehensions, similar to a list of understandings:
Object
Python supports most object-oriented programming techniques. This allows polymorphism, not only in the class hierarchy but also by typing ducks. Any object can be used for any type, and it will work as long as it has the right methods and attributes. And everything in Python is an object, including classes, functions, numbers and modules. Python also has support for metaclasses, a powerful tool for enhancing class functionality. Of course, inheritance, including multiple inheritance, is supported. It has limited support for private variables using the name of the deal. See the "Classroom" section of the tutorial for details. Many Python users do not feel the need for private variables. The slogan "We are all responsible users here" is used to describe this attitude. Some people consider the information to be hidden to be not embarrassing, because it indicates that the class in question contains internal that is not aesthetic or unplanned. However, the strongest argument for the name of the deal is the prevention of unpredictable program destruction: introducing a new public variable in superclass can break subclasses if they do not use the "private" variable.
From the tutorial: As true for the module, classes with Python do not place absolute barriers between definitions and users, but rather rely on the courtesy of users not to "get into definitions."
OOP doctrines such as the use of accessor methods to read member data are not enforced in Python. Just as Python offers functional-programming constructs but does not seek to demand referential transparency, it offers an object system but does not demand OOP behavior. In addition, it is always possible to redefine the class using properties so that when a particular variable is set or retrieved in the calling code, it actually calls the function call, so spam.eggs = toast
may actually call spam.set_eggs (toast)
. This cancels the practical benefits of accessor functions, and remains OOP because the eggs
property becomes a valid part of the object interface: it does not need to reflect implementation details.
In version 2.2 of Python, a "new style" class was introduced. With new style classes, objects and types are put together, allowing subclassing of types. Even completely new types can be defined, complete with special behavior for infix operators. This allows many things radically done syntactically in Python. New method resolution commands for multiple inheritance are also adopted in Python 2.3. It is also possible to run custom code when accessing or setting attributes, although details of the technique have evolved between versions of Python.
With statement
The statement "with" handles resources. One function is called when entering the scope and the other when away. It prevents forgetting to remove resources and also handles more complicated situations like exceptions.
Properties
The property allows specific methods specified to be called on an object instance by using the same syntax as used for access attributes. Examples of classes that define some properties are:
Descriptors
Classes that define one or more of the special methods <__ get __ (self, example, owner), __set __ (self, example, value), __delete __ (self, instance) can be used as a descriptor. Creating an instance descriptor as a class member of a second class makes the instance a property of the second class.
Class and static methods
Python allows the creation of class methods and static methods through the use of the @classmethod and @staticmethod decorators. The first argument to the class method is a class object, not a self-reference to an instance. Static methods do not have a special first argument. Neither the instance, nor the class object passed to the static method.
Exceptions
Python supports (and extensively uses) exception handling as a testing tool for error conditions and other "extraordinary" events in a program. Indeed, it is even possible to trap an exception caused by a syntax error.
The Python style calls for the use of exceptions each time an error condition may appear. Instead of testing for access to files or resources before actually using them, it's conventional in Python to go ahead and try to use them, catching an exception if access is denied.
Exceptions can also be used as a more common means of non-local transfer, even when errors are not at issue. For example, Mailman mailing list software, written in Python, uses exceptions to jump out of nested message handling logic when a decision has been made to reject messages or hold them for moderator approval.
Exceptions are often used as an alternative to if
-block, especially in threaded situations. Commonly used motto is EAFP, or "Easier Requesting Forgiveness than Permission," which is associated with Grace Hopper. Alternatively, known as LBYL, or "Look Before You Leap", explicitly test for pre-conditions.
In this first code example, following the LBYL approach, there is an explicit check for attributes before access:
This second sample follows the EAFP paradigm:
Both examples of this code have the same effect, although there will be performance differences. When spam
has the eggs
attribute, the EAFP sample will run faster. When spam
does not have the egg
attribute ("exceptional" case), the EAFP sample will run slower. The Python profiler can be used in certain cases to determine performance characteristics. If exceptional cases are rare, then the EAFP version will have an average performance that is superior to the alternatives. In addition, it avoids all of the time-of-check-to-time-of-use (TOCTTOU) classes of vulnerability, other race conditions, and is compatible with duck typing. The drawback of EAFP is that it can only be used with statements; exceptions can not be captured in generator expressions, list comprehension, or lambda functions.
Comments and docstrings
Python has two ways to annotate Python code. One is to use a comment to show what some of the code is doing. The one-line comment starts with a hash character ("#") and ends at the end of the line. Comments that include more than one line can be accomplished by entering a multi-line string (with "" "
as a barrier at each end) that is not used in a task or evaluated, but sitting between other statements.
Commented on a piece of code:
Comment on a piece of code with multiple lines:
Docstrings (string documentation), ie strings placed alone without assignment as the first indent line in the module, class, method or function, automatically organize its content as an attribute named __ doc __
, which is intended to store the description human readable about the purpose, behavior, and use of objects. The built-in help
function generates output based on the __ doc __
attribute. Such strings may be limited to "
or '
for a single line string, or may reach multiple lines if limited by " ""
or '' '
which is a Python notation for defining multi-line strings. However, style guides for languages ââspecify that three double quotes ( "" "
) are preferred for both single and multi-line documents.
Single path docstring:
Multi-garis docstring:
Docstrings can be as big as desired by the programmer and contain line breaks. Unlike comments, docstrings themselves are Python objects and are part of the interpreted code that Python executes. That means that running programs can retrieve their own documents and manipulate the information. But normal use is to provide other programmers information about how to call the documented object in the docstring.
There are tools available that can extract docstrings to generate the API documentation from the code. Documentation of the documentation can also be accessed from the interpreter with the function help ()
, or from the shell with the pydoc pydoc
command.
The standard doctest module uses interactions copied from a Python shell session to a docstring, to create a test.
Annotation function
Annotation functions are defined in PEP 3107. They allow attaching data to arguments and function returns. The annotation behavior is not defined by language, and submitted to third-party frameworks. For example, libraries can be written to handle static typing:
Decorator
A decorator is a callable Python object that is used to modify a function, method, or class definition. The decorator is passed the original object that is defined and returns the modified object, which is then bound to the name in the definition. Python decorators are inspired in part by Java annotations, and have similar syntax; decorator syntax is pure syntactic sugar, using @
as the keyword:
equal to
Decorators are a form of metaprogramming; they increase the action of the function or method they are decorating. For example, in the example below, viking_chorus
might cause menu_item
to run 8 times (see Spam sketch) for each call:
The canonical use of the function designers is to create class methods or static methods, add functional attributes, tracking, pre-and post-conditions settings, and sync, but can be used for far more than, including removal of tail recursion, memoisasi and even increase decorator writing.
Decorators can be chained by placing some on adjacent lines:
equal to
or, using an intermediary variable
In the example above, the decorator factory favorites_colour
takes the argument. The decorator should return the decorator, which is then called the object to be decorated as the argument:
This will then adorn the black_knight
function so the color, "Blue", will be printed before the black_knight
function runs. Closure ensures that color arguments can be accessed by the innermost wrapper function even when returned and out of scope, allowing the decorator to work.
In Python before version 2.6, the decorator applies to functions and methods, but not to classes. However, the decorating method (dummy) __ new __
can modify the class. The classroom decorator is supported starting with Python 2.6.
Despite its name, the Python decorator is not an implementation of the decorator pattern. Decorator patterns are design patterns used in statically typed object-oriented programming languages ââto allow functionality added to objects at run time; Python Decorators add functionality to functions and methods at the time of definition, and thus a higher level construct than the decorator class. The decorator pattern itself is trivially implemented in Python, because the language is typed duck, and it is usually not considered that way.
Easter Egg
Users of the square bracket programming language, such as C or Java, sometimes hope or expect Python to follow the blocking constraint. Block-separated block syntax has been repeatedly requested, and is consistently rejected by core developers. The Python translator contains an Easter egg that summarizes the developer's feelings about the issue. The code of __future__ import braces
raises an exception SyntaxError: not a chance
. The __ future __
module is usually used to provide features of future Python versions.
Another hidden message, The Zen of Python (a summary of Python philosophy), is displayed when trying importing this
.
Message Hello world!
is printed when the import statement import __hello __
is used. In Python 2.7, not Hello world!
he printed Hello world...
.
The antigravity
module is added to Python 2.7 and 3.0. Importing it opens a web browser for comic xkcd 353 that describes funny fictitious use for such modules, intended to show the convenience of Python modules that enable additional functionality. In Python 3.0, this module also contains an implementation of the "geohash" algorithm, a reference to xkcd comic 426.
References
External links
- Python Tutorial written by the author of Python, Guido van Rossum.
Source of the article : Wikipedia