Python syntax and semantics![]() The syntax of the Python programming language is the set of rules that defines how a Python program will be written and interpreted (by both the runtime system and by human readers). The Python language has many similarities to Perl, C, and Java. However, there are some definite differences between the languages. It supports multiple programming paradigms, including structured, object-oriented programming, and functional programming, and boasts a dynamic type system and automatic memory management. Python's syntax is simple and consistent, adhering to the principle that "There should be one— and preferably only one —obvious way to do it." The language incorporates built-in data types and structures, control flow mechanisms, first-class functions, and modules for better code reusability and organization. Python also uses English keywords where other languages use punctuation, contributing to its uncluttered visual layout. The language provides robust error handling through exceptions, and includes a debugger in the standard library for efficient problem-solving. Python's syntax, designed for readability and ease of use, makes it a popular choice among beginners and professionals alike. Design philosophyPython was designed to be a highly readable language.[1] It has a relatively uncluttered visual layout and uses English keywords frequently where other languages use punctuation. Python aims to be simple and consistent in the design of its syntax, encapsulated in the mantra "There should be one— and preferably only one —obvious way to do it", from the Zen of Python.[2] This mantra is deliberately opposed to the Perl and Ruby mantra, "there's more than one way to do it". KeywordsPython has 35 keywords or reserved words; they cannot be used as identifiers.[3][4] In addition, Python also has 3 soft keywords. Unlike regular hard keywords, soft keywords are reserved words only in the limited contexts where interpreting them as keywords would make syntactic sense. These words can be used as identifiers elsewhere, in other words, match and case are valid names for functions and variables.[6][7]
IndentationPython uses whitespace to delimit control flow blocks (following the off-side rule). Python borrows this feature from its predecessor ABC: instead of punctuation or keywords, it uses indentation to indicate the run of a block. In so-called "free-format" languages—that use the block structure derived from ALGOL—blocks of code are set off with braces ( A recursive function named def foo(x):
if x == 0:
bar()
else:
baz(x)
foo(x - 1)
and could be written like this in C with K&R indent style: void foo(int x)
{
if (x == 0) {
bar();
} else {
baz(x);
foo(x - 1);
}
}
Incorrectly indented code could be misread by a human reader differently than it would be interpreted by a compiler or interpreter. For example, if the function call def foo(x):
if x == 0:
bar()
else:
baz(x)
foo(x - 1)
it would cause the last line to always be executed, even when While both space and tab characters are accepted as forms of indentation and any multiple of spaces can be used, spaces are recommended[8] and 4 spaces (as in the above examples) are recommended and are by far the most commonly used.[9][10][unreliable source?] Mixing spaces and tabs on consecutive lines is not allowed starting with Python 3[11] because that can create bugs which are difficult to see, since many text editors do not visually distinguish spaces and tabs. Data structuresSince Python is a dynamically-typed language, Python values, not variables, carry type information. All variables in Python hold references to objects, and these references are passed to functions. Some people (including Guido van Rossum himself) have called this parameter-passing scheme "call by object reference". An object reference means a name, and the passed reference is an "alias", i.e. a copy of the reference to the same object, just as in C/C++. The object's value may be changed in the called function with the "alias", for example: >>> alist = ['a', 'b', 'c']
>>> def my_func(al):
... al.append('x')
... print(al)
...
>>> my_func(alist)
['a', 'b', 'c', 'x']
>>> alist
['a', 'b', 'c', 'x']
Function >>> alist = ['a', 'b', 'c']
>>> def my_func(al):
... # al.append('x')
... al = al + ['x'] # a new list created and assigned to al means al is no more alias for alist
... print(al)
...
>>> my_func(alist)
['a', 'b', 'c', 'x']
>>> print(alist)
['a', 'b', 'c']
In Python, non-innermost-local and not-declared-global accessible names are all aliases. Among dynamically-typed languages, Python is moderately type-checked. Implicit conversion is defined for numeric types (as well as booleans), so one may validly multiply a complex number by an integer (for instance) without explicit casting. However, there is no implicit conversion between, for example, numbers and strings; a string is an invalid argument to a mathematical function expecting a number. Base typesPython has a broad range of basic data types. Alongside conventional integer and floating-point arithmetic, it transparently supports arbitrary-precision arithmetic, complex numbers, and decimal numbers. Python supports a wide variety of string operations. Strings in Python are immutable, so a string operation such as a substitution of characters, that in other programming languages might alter the string in place, returns a new string in Python. Performance considerations sometimes push for using special techniques in programs that modify strings intensively, such as joining character arrays into strings only as needed. Collection typesOne of the very useful aspects of Python is the concept of collection (or container) types. In general a collection is an object that contains other objects in a way that is easily referenced or indexed. Collections come in two basic forms: sequences and mappings. The ordered sequential types are lists (dynamic arrays), tuples, and strings. All sequences are indexed positionally (0 through length - 1) and all but strings can contain any type of object, including multiple types in the same sequence. Both strings and tuples are immutable, making them perfect candidates for dictionary keys (see below). Lists, on the other hand, are mutable; elements can be inserted, deleted, modified, appended, or sorted in-place. Mappings, on the other hand, are (often unordered) types implemented in the form of dictionaries which "map" a set of immutable keys to corresponding elements (much like a mathematical function). For example, one could define a dictionary having a string Dictionaries are central to the internals of Python as they reside at the core of all objects and classes: the mappings between variable names (strings) and the values which the names reference are stored as dictionaries (see Object system). Since these dictionaries are directly accessible (via an object's A set collection type is an unindexed, unordered collection that contains no duplicates, and implements set theoretic operations such as union, intersection, difference, symmetric difference, and subset testing. There are two types of sets: Python also provides extensive collection manipulating abilities such as built in containment checking and a generic iteration protocol. Object systemIn Python, everything is an object, even classes. Classes, as objects, have a class, which is known as their metaclass. Python also supports multiple inheritance and mixins. The language supports extensive introspection of types and classes. Types can be read and compared—types are instances of Operators can be overloaded in Python by defining special member functions—for instance, defining a method named LiteralsStringsPython has various kinds of string literals. Normal string literalsEither single or double quotes can be used to quote strings. Unlike in Unix shell languages, Perl or Perl-influenced languages such as Ruby or Groovy, single quotes and double quotes function identically, i.e. there is no string interpolation of $foo expressions. However, interpolation can be done in various ways: with "f-strings" (since Python 3.6[12]), using the For instance, all of these Python statements: print(f"I just printed {num} pages to the printer {printer}")
print("I just printed {} pages to the printer {}".format(num, printer))
print("I just printed {0} pages to the printer {1}".format(num, printer))
print("I just printed {num} pages to the printer {printer}".format(num=num, printer=printer))
print("I just printed %s pages to the printer %s" % (num, printer))
print("I just printed %(num)s pages to the printer %(printer)s" % {"num": num, "printer": printer})
are equivalent to the Perl statement: print "I just printed $num pages to the printer $printer\n"
They build a string using the variables Multi-line string literalsThere are also multi-line strings, which begin and end with a series of three single or double quotes and function like here documents in Perl and Ruby. A simple example with variable interpolation (using the print('''Dear {recipient},
I wish you to leave Sunnydale and never return.
Not Quite Love,
{sender}
'''.format(sender="Buffy the Vampire Slayer", recipient="Spike"))
Raw stringsFinally, all of the previously mentioned string types come in "raw" varieties (denoted by placing a literal r before the opening quote), which do no backslash-interpolation and hence are very useful for regular expressions; compare "@-quoting" in C#. Raw strings were originally included specifically for regular expressions. Due to limitations of the tokenizer, raw strings may not have a trailing backslash.[13] Creating a raw string holding a Windows path ending with a backslash requires some variety of workaround (commonly, using forward slashes instead of backslashes, since Windows accepts both). Examples include: >>> # A Windows path, even raw strings cannot end in a backslash
>>> r"C:\Foo\Bar\Baz\"
File "<stdin>", line 1
r"C:\Foo\Bar\Baz\"
^
SyntaxError: EOL while scanning string literal
>>> dos_path = r"C:\Foo\Bar\Baz\ " # avoids the error by adding
>>> dos_path.rstrip() # and removing trailing space
'C:\\Foo\\Bar\\Baz\\'
>>> quoted_dos_path = r'"{}"'.format(dos_path)
>>> quoted_dos_path
'"C:\\Foo\\Bar\\Baz\\ "'
>>> # A regular expression matching a quoted string with possible backslash quoting
>>> re.match(r'"(([^"\\]|\\.)*)"', quoted_dos_path).group(1).rstrip()
'C:\\Foo\\Bar\\Baz\\'
>>> code = 'foo(2, bar)'
>>> # Reverse the arguments in a two-arg function call
>>> re.sub(r'\(([^,]*?),([^ ,]*?)\)', r'(\2, \1)', code)
'foo(2, bar)'
>>> # Note that this won't work if either argument has parens or commas in it.
Concatenation of adjacent string literalsString literals (using possibly different quote conventions) appearing contiguously and only separated by whitespace (including new lines), are allowed and are aggregated into a single longer string.[14] Thus title = "One Good Turn: " \
'A Natural History of the Screwdriver and the Screw'
is equivalent to title = "One Good Turn: A Natural History of the Screwdriver and the Screw"
UnicodeSince Python 3.0, the default character set is UTF-8 both for source code and the interpreter. In UTF-8, unicode strings are handled like traditional byte strings. This example will work: s = "Γειά" # Hello in Greek
print(s)
NumbersNumeric literals in Python are of the normal sort, e.g. Python has arbitrary-length integers and automatically increases their storage size as necessary. Prior to Python 3, there were two kinds of integral numbers: traditional fixed size integers and "long" integers of arbitrary size. The conversion to "long" integers was performed automatically when required, and thus the programmer usually didn't have to be aware of the two integral types. In newer language versions the distinction is completely gone and all integers behave like arbitrary-length integers. Python supports normal floating point numbers, which are created when a dot is used in a literal (e.g. Python also supports complex numbers natively. Complex numbers are indicated with the Lists, tuples, sets, dictionariesPython has syntactic support for the creation of container types. Lists (class a_list = [1, 2, 3, "a dog"]
or using normal object creation a_second_list = []
a_second_list.append(4)
a_second_list.append(5)
Tuples (class a_tuple = 1, 2, 3, "four"
a_tuple = (1, 2, 3, "four")
Although tuples are created by separating items with commas, the whole construct is usually wrapped in parentheses to increase readability. An empty tuple is denoted by Sets (class some_set = {0, (), False}
Python sets are very much like mathematical sets, and support operations like set intersection and union. Python also features a Dictionaries (class a_dictionary = {"key 1": "value 1", 2: 3, 4: []}
The dictionary syntax is similar to the set syntax, the difference is the presence of colons. The empty literal OperatorsArithmeticPython includes the In Python 3, >>> 4 / 2
2.0
and In Python 2 (and most other programming languages), unless explicitly requested, Comparison operatorsThe comparison operators, i.e. Chained comparison expressions such as For expressions without side effects, Logical operatorsIn all versions of Python, boolean operators treat zero values or empty values such as The boolean operators Functional programmingA strength of Python is the availability of a functional programming style, which makes working with lists and other collections much more straightforward. ComprehensionsOne such construction is the list comprehension, which can be expressed with the following format: L = [mapping_expression for element in source_list if filter_expression]
Using list comprehension to calculate the first five powers of two: powers_of_two = [2**n for n in range(1, 6)]
The Quicksort algorithm can be expressed elegantly (albeit inefficiently) using list comprehensions: def qsort(L):
if L == []:
return []
pivot = L[0]
return (qsort([x for x in L[1:] if x < pivot]) +
[pivot] +
qsort([x for x in L[1:] if x >= pivot]))
Python 2.7+[17] also supports set comprehensions[18] and dictionary comprehensions.[19] First-class functionsIn Python, functions are first-class objects that can be created and passed around dynamically. Python's limited support for anonymous functions is the f = lambda x: x**2
f(5)
Lambdas are limited to containing an expression rather than statements, although control flow can still be implemented less elegantly within lambda by using short-circuiting,[20] and more idiomatically with conditional expressions.[21] ClosuresPython has had support for lexical closures since version 2.2. Here's an example function that returns a function that approximates the derivative of the given function: def derivative(f, dx):
"""Return a function that approximates the derivative of f
using an interval of dx, which should be appropriately small.
"""
def function(x):
return (f(x + dx) - f(x)) / dx
return function
Python's syntax, though, sometimes leads programmers of other languages to think that closures are not supported. Variable scope in Python is implicitly determined by the scope in which one assigns a value to the variable, unless scope is explicitly declared with Note that the closure's binding of a name to some value is not mutable from within the function. Given: >>> def foo(a, b):
... print(f'a: {a}')
... print(f'b: {b}')
... def bar(c):
... b = c
... print(f'b*: {b}')
... bar(a)
... print(f'b: {b}')
...
>>> foo(1, 2)
a: 1
b: 2
b*: 1
b: 2
and you can see that GeneratorsIntroduced in Python 2.2 as an optional feature and finalized in version 2.3, generators are Python's mechanism for lazy evaluation of a function that would otherwise return a space-prohibitive or computationally intensive list. This is an example to lazily generate the prime numbers: from itertools import count
def generate_primes(stop_at=None):
primes = []
for n in count(start=2):
if stop_at is not None and n > stop_at:
return # raises the StopIteration exception
composite = False
for p in primes:
if not n % p:
composite = True
break
elif p ** 2 > n:
break
if not composite:
primes.append(n)
yield n
When calling this function, the returned value can be iterated over much like a list: for i in generate_primes(100): # iterate over the primes between 0 and 100
print(i)
for i in generate_primes(): # iterate over ALL primes indefinitely
print(i)
The definition of a generator appears identical to that of a function, except the keyword Generators don't have to be infinite like the prime-number example above. When a generator terminates, an internal exception is raised which indicates to any calling context that there are no more values. A Generator expressionsIntroduced in Python 2.4, generator expressions are the lazy evaluation equivalent of list comprehensions. Using the prime number generator provided in the above section, we might define a lazy, but not quite infinite collection. from itertools import islice
primes_under_million = (i for i in generate_primes() if i < 1000000)
two_thousandth_prime = islice(primes_under_million, 1999, 2000).next()
Most of the memory and time needed to generate this many primes will not be used until the needed element is actually accessed. Unfortunately, you cannot perform simple indexing and slicing of generators, but must use the itertools module or "roll your own" loops. In contrast, a list comprehension is functionally equivalent, but is greedy in performing all the work: primes_under_million = [i for i in generate_primes(2000000) if i < 1000000]
two_thousandth_prime = primes_under_million[1999]
The list comprehension will immediately create a large list (with 78498 items, in the example, but transiently creating a list of primes under two million), even if most elements are never accessed. The generator comprehension is more parsimonious. Dictionary and set comprehensionsWhile lists and generators had comprehensions/expressions, in Python versions older than 2.7 the other Python built-in collection types (dicts and sets) had to be kludged in using lists or generators: >>> dict((n, n*n) for n in range(5))
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
Python 2.7 and 3.0 unified all collection types by introducing dictionary and set comprehensions, similar to list comprehensions: >>> [n*n for n in range(5)] # regular list comprehension
[0, 1, 4, 9, 16]
>>>
>>> {n*n for n in range(5)} # set comprehension
{0, 1, 4, 9, 16}
>>>
>>> {n: n*n for n in range(5)} # dict comprehension
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
ObjectsPython supports most object oriented programming (OOP) techniques. It allows polymorphism, not only within a class hierarchy but also by duck typing. Any object can be used for any type, and it will work so long as it has the proper methods and attributes. And everything in Python is an object, including classes, functions, numbers and modules. Python also has support for metaclasses, an advanced tool for enhancing classes' functionality. Naturally, inheritance, including multiple inheritance, is supported. Python has very limited support for private variables using name mangling which is rarely used in practice as information hiding is seen by some as unpythonic, in that it suggests that the class in question contains unaesthetic or ill-planned internals. The slogan "we're all responsible users here" is used to describe this attitude.[23]
OOP doctrines such as the use of accessor methods to read data members are not enforced in Python. Just as Python offers functional-programming constructs but does not attempt to demand referential transparency, it offers an object system but does not demand OOP behavior. Moreover, it is always possible to redefine the class using properties (see Properties) so that when a certain variable is set or retrieved in calling code, it really invokes a function call, so that In version 2.2 of Python, "new-style" classes were introduced. With new-style classes, objects and types were unified, allowing the subclassing of types. Even entirely new types can be defined, complete with custom behavior for infix operators. This allows for many radical things to be done syntactically within Python. A new method resolution order for multiple inheritance was also adopted with Python 2.3. It is also possible to run custom code while accessing or setting attributes, though the details of those techniques have evolved between Python versions. With statementThe PropertiesProperties allow specially defined methods to be invoked on an object instance by using the same syntax as used for attribute access. An example of a class defining some properties is: class MyClass:
def __init__(self):
self._a = None
@property
def a(self):
return self._a
@a.setter # makes the property writable
def a(self, value):
self._a = value
DescriptorsA class that defines one or more of the three special methods Class and static methodsPython allows the creation of class methods and static methods via the use of the ExceptionsPython supports (and extensively uses) exception handling as a means of testing for error conditions and other "exceptional" events in a program. Python style calls for the use of exceptions whenever an error condition might arise. Rather than testing for access to a file or resource before actually using it, it is conventional in Python to just go ahead and try to use it, catching the exception if access is rejected. Exceptions can also be used as a more general means of non-local transfer of control, even when an error is not at issue. For instance, the Mailman mailing list software, written in Python, uses exceptions to jump out of deeply nested message-handling logic when a decision has been made to reject a message or hold it for moderator approval. Exceptions are often used as an alternative to the In this first code sample, following the LBYL approach, there is an explicit check for the attribute before access: if hasattr(spam, 'eggs'):
ham = spam.eggs
else:
handle_missing_attr()
This second sample follows the EAFP paradigm: try:
ham = spam.eggs
except AttributeError:
handle_missing_attr()
These two code samples have the same effect, although there will be performance differences. When Comments and docstringsPython has two ways to annotate Python code. One is by using comments to indicate what some part of the code does. Single-line comments begin with the hash character ( Commenting a piece of code: import sys
def getline():
return sys.stdin.readline() # Get one line and return it
Commenting a piece of code with multiple lines: def getline():
"""This function gets one line and returns it.
As a demonstration, this is a multiline docstring.
This full string can be accessed as getline.__doc__.
"""
return sys.stdin.readline()
Docstrings (documentation strings), that is, strings that are located alone without assignment as the first indented line within a module, class, method or function, automatically set their contents as an attribute named Single-line docstring: def getline():
"""Get one line from stdin and return it."""
return sys.stdin.readline()
Multi-line docstring: def getline():
"""Get one line
from stdin
and return it.
"""
return sys.stdin.readline()
Docstrings can be as large as the programmer wants and contain line breaks. In contrast with comments, docstrings are themselves Python objects and are part of the interpreted code that Python runs. That means that a running program can retrieve its own docstrings and manipulate that information, but the normal usage is to give other programmers information about how to invoke the object being documented in the docstring. There are tools available that can extract the docstrings from Python code and generate documentation. Docstring documentation can also be accessed from the interpreter with the The doctest standard module uses interactions copied from Python shell sessions into docstrings to create tests, whereas the docopt module uses them to define command-line options. Function annotationsFunction annotations (type hints) are defined in PEP 3107.[32] They allow attaching data to the arguments and return of a function. The behaviour of annotations is not defined by the language, and is left to third party frameworks. For example, a library could be written to handle static typing:[32] def haul(item: Haulable, *vargs: PackAnimal) -> Distance
DecoratorsA decorator is any callable Python object that is used to modify a function, method or class definition. A decorator is passed the original object being defined and returns a modified object, which is then bound to the name in the definition. Python decorators were inspired in part by Java annotations, and have a similar syntax; the decorator syntax is pure syntactic sugar, using @viking_chorus
def menu_item():
print("spam")
is equivalent to def menu_item():
print("spam")
menu_item = viking_chorus(menu_item)
Decorators are a form of metaprogramming; they enhance the action of the function or method they decorate. For example, in the sample below, def viking_chorus(myfunc):
def inner_func(*args, **kwargs):
for i in range(8):
myfunc(*args, **kwargs)
return inner_func
Canonical uses of function decorators are for creating class methods or static methods, adding function attributes, tracing, setting pre- and postconditions, and synchronization,[33] but can be used for far more, including tail recursion elimination,[34] memoization and even improving the writing of other decorators.[35] Decorators can be chained by placing several on adjacent lines: @invincible
@favourite_colour("Blue")
def black_knight():
pass
is equivalent to def black_knight():
pass
black_knight = invincible(favourite_colour("Blue")(black_knight))
or, using intermediate variables def black_knight():
pass
blue_decorator = favourite_colour("Blue")
decorated_by_blue = blue_decorator(black_knight)
black_knight = invincible(decorated_by_blue)
In the example above, the def favourite_colour(colour):
def decorator(func):
def wrapper():
print(colour)
func()
return wrapper
return decorator
This would then decorate the Despite the name, Python decorators are not an implementation of the decorator pattern. The decorator pattern is a design pattern used in statically-typed object-oriented programming languages to allow functionality to be added to objects at run time; Python decorators add functionality to functions and methods at definition time, and thus are a higher-level construct than decorator-pattern classes. The decorator pattern itself is trivially implementable in Python, because the language is duck typed, and so is not usually considered as such.[clarification needed] Easter eggsUsers of curly bracket languages, such as C or Java, sometimes expect or wish Python to follow a block-delimiter convention. Brace-delimited block syntax has been repeatedly requested, and consistently rejected by core developers. The Python interpreter contains an easter egg that summarizes its developers' feelings on this issue. The code Another hidden message, the Zen of Python (a summary of Python design philosophy), is displayed when trying to The message Importing the References
External links
|
Portal di Ensiklopedia Dunia