Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Python (programming language)
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
==Syntax and semantics== {{Main|Python syntax and semantics}} [[File:Hello World in Python.png|alt=Block of Python code showing sample source code|thumb|231x231px|An example of Python code and indentation]] [[File:Af-Helloworld (C Sharp).svg|alt=C code featuring curly braces and semicolon|thumb|233x233px|Example of [[C Sharp (programming language)|C#]] code with curly braces and semicolons]] Python is meant to be an easily readable language. Its formatting is visually uncluttered and often uses English keywords where other languages use punctuation. Unlike many other languages, it does not use [[curly bracket programming language|curly brackets]] to delimit blocks, and semicolons after statements are allowed but rarely used. It has fewer syntactic exceptions and special cases than [[C (programming language)|C]] or [[Pascal (programming language)|Pascal]].<ref name="AutoNT-52"/> ===Indentation=== {{Main|Python syntax and semantics#Indentation}} Python uses [[whitespace character|whitespace]] indentation, rather than curly brackets or keywords, to delimit [[block (programming)|blocks]]. An increase in indentation comes after certain statements; a decrease in indentation signifies the end of the current block.<ref name="AutoNT-53"/> Thus, the program's visual structure accurately represents its semantic structure.<ref name=guttag>{{Cite book |publisher=MIT Press |isbn=978-0-262-52962-4 |last=Guttag |first=John V. |title=Introduction to Computation and Programming Using Python: With Application to Understanding Data |date=12 August 2016}}</ref> This feature is sometimes termed the [[off-side rule]]. Some other languages use indentation this way; but in most, indentation has no semantic meaning. The recommended indent size is four spaces.<ref>{{Cite web|url=https://www.python.org/dev/peps/pep-0008/|title=PEP 8 – Style Guide for Python Code|website=Python.org|access-date=26 March 2019|archive-date=17 April 2019|archive-url=https://web.archive.org/web/20190417223549/https://www.python.org/dev/peps/pep-0008/|url-status=live}}</ref> ===Statements and control flow=== Python's [[statement (computer science)|statements]] include the following: * The [[Assignment (computer science)|assignment]] statement, using a single equals sign <code>=</code> * The <code>[[if-then-else|if]]</code> statement, which conditionally executes a block of code, along with <code>else</code> and <code>elif</code> (a contraction of <code>else if</code>) * The <code>[[Foreach#Python|for]]</code> statement, which iterates over an ''iterable'' object, capturing each element to a local variable for use by the attached block * The <code>[[While loop#Python|while]]</code> statement, which executes a block of code as long as its condition is true * The <code>[[Exception handling syntax#Python|try]]</code> statement, which allows exceptions raised in its attached code block to be caught and handled by <code>except</code> clauses (or new syntax <code>except*</code> in Python 3.11 for exception groups<ref>{{Cite web |title=8. Errors and Exceptions – Python 3.12.0a0 documentation |url=https://docs.python.org/3.11/tutorial/errors.html |access-date=2022-05-09 |website=docs.python.org |archive-date=9 May 2022 |archive-url=https://web.archive.org/web/20220509145745/https://docs.python.org/3.11/tutorial/errors.html |url-status=live}}</ref>); the <code>try</code> statement also ensures that clean-up code in a <code>finally</code> block is always run regardless of how the block exits * The <code>raise</code> statement, used to raise a specified exception or re-raise a caught exception * The <code>class</code> statement, which executes a block of code and attaches its local namespace to a [[class (computer science)|class]], for use in object-oriented programming * The <code>def</code> statement, which defines a [[function (computing)|function]] or [[method (computing)|method]] * The <code>[[dispose pattern#Language constructs|with]]</code> statement, which encloses a code block within a context manager, allowing [[resource acquisition is initialization|resource-acquisition-is-initialization]] (RAII)-like behavior and replacing a common try/finally idiom<ref>{{cite web|url=https://www.python.org/download/releases/2.5/highlights/|title=Highlights: Python 2.5|website=Python.org|access-date=20 March 2018|archive-date=4 August 2019|archive-url=https://web.archive.org/web/20190804120408/https://www.python.org/download/releases/2.5/highlights/|url-status=live}}</ref> Examples of a context include acquiring a [[lock (computer science)|lock]] before some code is run, and then releasing the lock; or opening and then closing a [[Computer file|file]] * The <code>[[break statement|break]]</code> statement, which exits a loop * The <code>continue</code> statement, which skips the rest of the current iteration and continues with the next * The <code>del</code> statement, which removes a variable—deleting the reference from the name to the value, and producing an error if the variable is referred to before it is redefined {{efn|<code>del</code> in Python does not behave the same way <code>delete</code> in languages such as [[C++]] does, where such a word is used to call the [[Destructor (computer programming)|destructor]] and deallocate heap memory.}} * The <code>pass</code> statement, serving as a [[NOP (code)|NOP]] (i.e., no operation), which is syntactically needed to create an empty code block * The <code>[[assertion (programming)|assert]]</code> statement, used in debugging to check for conditions that should apply * The <code>yield</code> statement, which returns a value from a [[generator (computer programming)#Python|generator]] function (and also an operator); used to implement [[coroutine]]s * The <code>return</code> statement, used to return a value from a function * The <code>[[include directive|import]]</code> and <code>from</code> statements, used to import modules whose functions or variables can be used in the current program * The <code>match</code> and <code>case</code> statements, analogous to a [[switch statement]] construct, which compares an expression against one or more cases as a control-flow measure The assignment statement (<code>=</code>) binds a name as a [[pointer (computer programming)|reference]] to a separate, dynamically allocated [[object (computer science)|object]]. Variables may subsequently be rebound at any time to any object. In Python, a variable name is a generic reference holder without a fixed [[Type system|data type]]; however, it always refers to ''some'' object with a type. This is called [[Type system#Dynamic type checking and runtime type information|dynamic typing]]—in contrast to [[statically-typed]] languages, where each variable may contain only a value of a certain type. Python does not support [[tail call]] optimization or [[first-class continuations]]; according to Van Rossum, the language never will.<ref name="AutoNT-55"/><ref name="AutoNT-56"/> However, better support for [[coroutine]]-like functionality is provided by extending Python's generators.<ref name="AutoNT-57"/> Before 2.5, generators were [[lazy evaluation|lazy]] [[iterator]]s; data was passed unidirectionally out of the generator. From Python 2.5 on, it is possible to pass data back into a generator function; and from version 3.3, data can be passed through multiple stack levels.<ref name="AutoNT-58"/> ===Expressions=== Python's [[expression (computer science)|expressions]] include the following: * The <code>+</code>, <code>-</code>, and <code>*</code> operators for mathematical addition, subtraction, and multiplication are similar to other languages, but the behavior of division differs. There are two types of division in Python: [[floor division]] (or integer division) <code>//</code>, and floating-point division <code>/</code>.<ref>{{cite web|title=division|url=https://docs.python.org|website=python.org|access-date=30 July 2014|archive-date=20 July 2006|archive-url=https://web.archive.org/web/20060720033244/http://docs.python.org/|url-status=live}}</ref> Python uses the <code>**</code> operator for exponentiation. * Python uses the <code>+</code> operator for string concatenation. The language uses the <code>*</code> operator for duplicating a string a specified number of times. * The <code>@</code> infix operator<!-- was introduced in Python 3.5--> is intended to be used by libraries such as [[NumPy]] for [[matrix multiplication]].<ref name=PEP465>{{cite web |title=PEP 0465 – A dedicated infix operator for matrix multiplication |url=https://www.python.org/dev/peps/pep-0465/ |website=python.org |access-date=1 January 2016 |archive-date=4 June 2020 |archive-url=https://web.archive.org/web/20200604224255/https://www.python.org/dev/peps/pep-0465/ |url-status=live}}</ref><ref name=Python3.5Changelog>{{cite web |title=Python 3.5.1 Release and Changelog |url=https://www.python.org/downloads/release/python-351/ |website=python.org |access-date=1 January 2016 |archive-date=14 May 2020 |archive-url=https://web.archive.org/web/20200514034938/https://www.python.org/downloads/release/python-351/ |url-status=live}}</ref> * The syntax <code>:=</code>, called the "walrus operator", was introduced in Python 3.8. This operator assigns values to variables as part of a larger expression.<ref name=Python3.8Changelog>{{cite web |title=What's New in Python 3.8 |url=https://docs.python.org/3.8/whatsnew/3.8.html |access-date=14 October 2019 |archive-date=8 June 2020 |archive-url=https://web.archive.org/web/20200608124345/https://docs.python.org/3.8/whatsnew/3.8.html |url-status=live}}</ref> * In Python, <code>==</code> compares two objects by value. Python's <code>is</code> operator may be used to compare object identities (i.e., comparison by reference), and comparisons may be chained—for example, {{code|lang=python|code=a <= b <= c}}. * Python uses <code>and</code>, <code>or</code>, and <code>not</code> as Boolean operators. * Python has a type of expression called a ''[[List comprehension#Python|list comprehension]]'', and a more general expression called a ''generator expression''.<ref name="AutoNT-59"/> * [[Anonymous function]]s are implemented using [[Lambda (programming)|lambda expressions]]; however, there may be only one expression in each body. * Conditional expressions are written as {{code|lang=python|code=x if c else y}}.<ref name="AutoNT-60"/> (This is different in operand order from the <code>[[?:|c ? x : y]]</code> operator common to many other languages.) * Python makes a distinction between [[list (computer science)|lists]] and [[tuple]]s. Lists are written as {{code|lang=python|code=[1, 2, 3]}}, are mutable, and cannot be used as the keys of dictionaries (since dictionary keys must be [[immutable]] in Python). Tuples, written as {{code|lang=python|code=(1, 2, 3)}}, are immutable and thus can be used as the keys of dictionaries, provided that all of the tuple's elements are immutable. The <code>+</code> operator can be used to concatenate two tuples, which does not directly modify their contents, but produces a new tuple containing the elements of both. For example, given the variable <code>t</code> initially equal to {{code|lang=python|code=(1, 2, 3)}}, executing {{code|lang=python|code=t = t + (4, 5)}} first evaluates {{code|lang=python|code=t + (4, 5)}}, which yields {{code|lang=python|code=(1, 2, 3, 4, 5)}}; this result is then assigned back to <code>t</code>—thereby effectively "modifying the contents" of <code>t</code> while conforming to the immutable nature of tuple objects. Parentheses are optional for tuples in unambiguous contexts.<ref>{{cite web|title=4. Built-in Types – Python 3.6.3rc1 documentation|url=https://docs.python.org/3/library/stdtypes.html#tuple|website=python.org|access-date=1 October 2017|archive-date=14 June 2020|archive-url=https://web.archive.org/web/20200614194325/https://docs.python.org/3/library/stdtypes.html#tuple|url-status=live}}</ref> * Python features ''sequence unpacking'' where multiple expressions, each evaluating to something assignable (e.g., a variable or a writable property) are associated just as in forming tuple literal; as a whole, the results are then put on the left-hand side of the equal sign in an assignment statement. This statement expects an ''iterable'' object on the right-hand side of the equal sign to produce the same number of values as the writable expressions on the left-hand side; while iterating, the statement assigns each of the values produced on the right to the corresponding expression on the left.<ref>{{cite web|title=5.3. Tuples and Sequences – Python 3.7.1rc2 documentation|url=https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences|website=python.org|access-date=17 October 2018|archive-date=10 June 2020|archive-url=https://web.archive.org/web/20200610050047/https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences|url-status=live}}</ref> * Python has a "string format" operator <code>%</code> that functions analogously to <code>[[printf]]</code> format strings in the C language—e.g. {{code|2=python|1="spam=%s eggs=%d" % ("blah", 2)}} evaluates to <code>"spam=blah eggs=2"</code>. In Python 2.6+ and 3+, this operator was supplemented by the <code>format()</code> method of the <code>str</code> class, e.g., {{code|2=python|1="spam={0} eggs={1}".format("blah", 2)}}. Python 3.6 added "f-strings": {{code|2=python|1=spam = "blah"; eggs = 2; f'spam={spam} eggs={eggs}'}}.<ref name="pep-0498">{{cite web |title=PEP 498 – Literal String Interpolation |url=https://www.python.org/dev/peps/pep-0498/ |website=python.org |access-date=8 March 2017 |archive-date=15 June 2020 |archive-url=https://web.archive.org/web/20200615184141/https://www.python.org/dev/peps/pep-0498/ |url-status=live}}</ref> * Strings in Python can be [[concatenated]] by "adding" them (using the same operator as for adding integers and floats); e.g., {{code|2=python|1="spam" + "eggs"}} returns <code>"spameggs"</code>. If strings contain numbers, they are concatenated as strings rather than as integers, e.g. {{code|2=python|1="2" + "2"}} returns <code>"22"</code>. * Python supports [[string literal]]s in several ways: ** Delimited by single or double quotation marks; single and double quotation marks have equivalent functionality (unlike in [[Unix shell]]s, [[Perl]], and Perl-influenced languages). Both marks use the backslash (<code>\</code>) as an [[escape character]]. [[String interpolation]] became available in Python 3.6 as "formatted string literals".<ref name="pep-0498"/> ** Triple-quoted, i.e., starting and ending with three single or double quotation marks; this may span multiple lines and function like [[here document]]s in shells, Perl, and [[Ruby (programming language)|Ruby]]. ** [[Raw string]] varieties, denoted by prefixing the string literal with <code>r</code>. Escape sequences are not interpreted; hence raw strings are useful where literal backslashes are common, such as in [[regular expression]]s and [[Windows]]-style paths. (Compare "<code>@</code>-quoting" in [[C Sharp (programming language)|C#]].) * Python has [[array index]] and [[array slicing]] expressions in lists, which are written as <code>a[key]</code>, {{code|lang=python|code=a[start:stop]}} or {{code|lang=python|code=a[start:stop:step]}}. Indexes are [[zero-based numbering|zero-based]], and negative indexes are relative to the end. Slices take elements from the ''start'' index up to, but not including, the ''stop'' index. The (optional) third slice [[Parameter (computer programming)|parameter]], called ''step'' or ''stride'', allows elements to be skipped or reversed. Slice indexes may be omitted—for example, {{code|lang=python|code=a[:]}} returns a copy of the entire list. Each element of a slice is a [[shallow copy]]. In Python, a distinction between expressions and statements is rigidly enforced, in contrast to languages such as [[Common Lisp]], [[Scheme (programming language)|Scheme]], or [[Ruby (programming language)|Ruby]]. This distinction leads to duplicating some functionality, for example: * [[List comprehensions]] vs. <code>for</code>-loops * [[Conditional (programming)|Conditional]] expressions vs. <code>if</code> blocks * The <code>eval()</code> vs. <code>exec()</code> built-in functions (in Python 2, <code>exec</code> is a statement); the former function is for expressions, while the latter is for statements A statement cannot be part of an expression; because of this restriction, expressions such as list and <code>dict</code> comprehensions (and lambda expressions) cannot contain statements. As a particular case, an assignment statement such as {{code|lang=python|code=a = 1}} cannot be part of the conditional expression of a conditional statement. ===Methods=== [[Method (computer programming)|Methods]] of objects are functions attached to the object's class; the syntax for normal methods and functions, {{code|lang=python|code=instance.method(argument)}}, is [[syntactic sugar]] for {{code|lang=python|code=Class.method(instance, argument)}}. Python methods have an explicit <code>[[this (computer programming)|self]]</code> parameter to access [[instance data]], in contrast to the implicit self (or <code>this</code>) parameter in some object-oriented programming languages (e.g., [[C++]], [[Java (programming language)|Java]], [[Objective-C]], [[Ruby (programming language)|Ruby]]).<ref name="AutoNT-61"/> Python also provides methods, often called ''dunder methods'' (because their names begin and end with double underscores); these methods allow user-defined classes to modify how they are handled by native operations including length, comparison, [[arithmetic operations|arithmetic]], and type conversion.<ref>{{cite book |last1=Sweigart |first1=Al |title=Beyond the Basic Stuff with Python: Best Practices for Writing Clean Code |year=2020 |publisher=No Starch Press |isbn=978-1-59327-966-0 |page=322 |url=https://books.google.com/books?id=7GUKEAAAQBAJ&pg=PA322 |language=en |access-date=7 July 2021 |archive-date=13 August 2021 |archive-url=https://web.archive.org/web/20210813194312/https://books.google.com/books?id=7GUKEAAAQBAJ&pg=PA322 |url-status=live}}</ref> ===Typing=== [[File:Python 3.13 Standrd Type Hierarchy-en.svg|thumb|The standard type hierarchy in Python 3]] Python uses [[duck typing]], and it has typed objects but untyped variable names. Type constraints are not checked at definition time; rather, operations on an object may fail at usage time, indicating that the object is not of an appropriate type. Despite being [[dynamically typed]], Python is [[strongly typed]], forbidding operations that are poorly defined (e.g., adding a number and a string) rather than quietly attempting to interpret them. Python allows programmers to define their own types using [[class (computer science)|classes]], most often for [[object-oriented programming]]. New [[object (computer science)|instances]] of classes are constructed by calling the class, for example, {{code|lang=python|code=SpamClass()}} or {{code|lang=python|code=EggsClass()}}); the classes are instances of the [[metaclass]] <code>type</code> (which is an instance of itself), thereby allowing metaprogramming and [[Reflective programming|reflection]]. Before version 3.0, Python had two kinds of classes, both using the same syntax: ''old-style'' and ''new-style''.<ref name="classy"/> Current Python versions support the semantics of only the new style. Python supports [[optional typing|optional type annotations]].<ref name="type_hint-PEP"/><ref>{{Cite web |title=PEP 484 – Type Hints {{!}} peps.python.org |url=https://peps.python.org/pep-0484/ |access-date=2023-11-29 |website=peps.python.org |archive-date=27 November 2023 |archive-url=https://web.archive.org/web/20231127205023/https://peps.python.org/pep-0484/ |url-status=live}}</ref> These annotations are not enforced by the language, but may be used by external tools such as '''mypy''' to catch errors.<ref>{{cite web |title=typing — Support for type hints |url=https://docs.python.org/3/library/typing.html |website=Python documentation |publisher=Python Software Foundation |access-date=22 December 2023 |archive-date=21 February 2020 |archive-url=https://web.archive.org/web/20200221184042/https://docs.python.org/3/library/typing.html |url-status=live}}</ref><ref>{{cite web |url=http://mypy-lang.org/ |title=mypy – Optional Static Typing for Python |access-date=28 January 2017 |archive-date=6 June 2020 |archive-url=https://web.archive.org/web/20200606192012/http://mypy-lang.org/ |url-status=live}}</ref> Mypy also supports a Python compiler called mypyc, which leverages type annotations for optimization.<ref>{{cite web |title=Introduction |url=https://mypyc.readthedocs.io/en/latest/introduction.html |website=mypyc.readthedocs.io |access-date=22 December 2023 |archive-date=22 December 2023 |archive-url=https://web.archive.org/web/20231222000457/https://mypyc.readthedocs.io/en/latest/introduction.html |url-status=live}}</ref> {|class="wikitable" |+ Summary of Python 3's built-in types |- ! Type ! [[immutable object|Mutability]] ! Description ! Syntax examples |- | <code>bool</code> | immutable | [[Boolean value]] | {{code|lang=python|True}}<br />{{code|lang=python|False}} |- | <code>bytearray</code> | mutable | Sequence of [[byte]]s | {{code|lang=python|bytearray(b'Some ASCII')}}<br />{{code|lang=python|bytearray(b"Some ASCII")}}<br />{{code|lang=python|bytearray([119, 105, 107, 105])}} |- | <code>bytes</code> | immutable | Sequence of bytes | {{code|lang=python|b'Some ASCII'}}<br />{{code|lang=python|b"Some ASCII"}}<br />{{code|lang=python|bytes([119, 105, 107, 105])}} |- | <code>complex</code> | immutable | [[Complex number]] with real and imaginary parts | {{code|lang=python|3+2.7j}}<br />{{code|lang=python|3 + 2.7j}} |- | <code>dict</code> | mutable | [[Associative array]] (or dictionary) of key and value pairs; can contain mixed types (keys and values); keys must be a hashable type | {{code|lang=python|{'key1': 1.0, 3: False} }}<br />{{code|lang=python| {} }} |- | <code>types.EllipsisType</code> | immutable | An [[Ellipsis (programming operator)|ellipsis]] placeholder to be used as an index in [[NumPy]] arrays | {{code|lang=python|...}}<br />{{code|lang=python|Ellipsis}} |- | <code>float</code> | immutable | [[Double-precision]] [[floating-point number]]. The precision is machine-dependent, but in practice it is generally implemented as a 64-bit [[IEEE 754]] number with 53 bits of precision.<ref>{{Cite web |title=15. Floating Point Arithmetic: Issues and Limitations – Python 3.8.3 documentation |url=https://docs.python.org/3.8/tutorial/floatingpoint.html#representation-error |access-date=6 June 2020 |website=docs.python.org |quote=Almost all machines today (November 2000) use IEEE-754 floating point arithmetic, and almost all platforms map Python floats to IEEE-754 "double precision". |archive-date=6 June 2020 |archive-url=https://web.archive.org/web/20200606113842/https://docs.python.org/3.8/tutorial/floatingpoint.html#representation-error |url-status=live }}</ref> | {{code|lang=python|1.33333}} |- | <code>frozenset</code> | immutable | Unordered [[set (computer science)|set]], contains no duplicates; can contain mixed types, if hashable | {{nobr|{{code|lang=python|frozenset([4.0, 'string', True])}}}} |- | <code>int</code> | immutable | [[Integer (computer science)|Integer]] of unlimited magnitude<ref name="pep0237"/> | {{code|lang=python|42}} |- | <code>list</code> | mutable | [[list (computer science)|List]], can contain mixed types | {{code|lang=python|[4.0, 'string', True]}}<br />{{code|lang=python|[]}} |- | <code>types.NoneType</code> | immutable | An object representing the absence of a value, often called [[null pointer|null]] in other languages | {{code|lang=python|None}} |- | <code>types.NotImplementedType</code> | immutable | A placeholder that can be returned from [[Operator overloading|overloaded operators]] to indicate unsupported operand types. | {{code|lang=python|NotImplemented}} |- | <code>range</code> | immutable | An ''immutable sequence'' of numbers, commonly used for iterating a specific number of times in <code>for</code> loops<ref>{{cite web |title=Built-in Types |url=https://docs.python.org/3/library/stdtypes.html#typesseq-range |access-date=3 October 2019 |archive-date=14 June 2020 |archive-url=https://web.archive.org/web/20200614194325/https://docs.python.org/3/library/stdtypes.html#typesseq-range |url-status=live}}</ref> | {{code|lang=python|range(−1, 10)}}<br />{{code|lang=python|range(10, −5, −2)}} |- | <code>set</code> | mutable | Unordered [[set (computer science)|set]], contains no duplicates; can contain mixed types, if hashable | {{code|lang=python| {4.0, 'string', True} }}<br />{{code|lang=python|set()}} |- | <code>str</code> | immutable | A [[character string]]: sequence of Unicode codepoints | {{code|lang=python|'Wikipedia'}}<br />{{code|lang=python|"Wikipedia"}}<syntaxhighlight lang="python">"""Spanning multiple lines"""</syntaxhighlight><syntaxhighlight lang="python"> Spanning multiple lines </syntaxhighlight> |- | <code>tuple</code> | immutable | [[Tuple]], can contain mixed types | {{code|lang=python|(4.0, 'string', True)}}<br />{{code|lang=python|('single element',)}}<br />{{code|lang=python|()}} |} ===Arithmetic operations=== Python includes conventional symbols for arithmetic operators (<code>+</code>, <code>-</code>, <code>*</code>, <code>/</code>), the floor-division operator <code>//</code>, and the [[modulo operation|modulo operator]] <code>%</code>. (With the module operator, a remainder can be negative,<!--unlike in C language depending on compiler,<ref>{{Cite web|url=https://stackoverflow.com/questions/11720656/modulo-operation-with-negative-numbers/42131603|title=c – Modulo operation with negative numbers|quote=Note that, in C89, whether the result round upward or downward is implementation-defined.|website=Stack Overflow|access-date=25 September 2019}}</ref>--> e.g., <code>4 % -3 == -2</code>.) Python also offers the <code>**</code> symbol for [[exponentiation]], e.g. <code>5**3 == 125</code> and <code>9**0.5 == 3.0</code>; it also offers the matrix‑multiplication operator <code>@</code> .<ref>{{cite web |url=https://legacy.python.org/dev/peps/pep-0465/ |title=PEP 465 – A dedicated infix operator for matrix multiplication |work=python.org |access-date=3 July 2018 |archive-date=29 May 2020 |archive-url=https://web.archive.org/web/20200529200310/https://legacy.python.org/dev/peps/pep-0465/ |url-status=live}}</ref> These operators work as in traditional mathematics; with the same [[order of operations|precedence rules]], the [[infix notation|infix]] operators <code>+</code> and <code>-</code> can also be [[unary operation|unary]], to represent positive and negative numbers respectively. Division between integers produces floating-point results. The behavior of division has changed significantly over time:<ref name="pep0238"/> * The current version of Python (i.e., since 3.0) changed <code>the /</code> operator to always represent floating-point division, e.g., {{code|class=nowrap|2=python|1=5/2 == 2.5}}. * The floor division <code>//</code> operator was introduced. Thus <code>7//3 == 2</code>, <code>-7//3 == -3</code>, <code>7.5//3 == 2.0</code>, and <code>-7.5//3 == -3.0</code>. For outdated Python 2.7 adding the {{code|class=nowrap|2=python2|1=from __future__ import division}} statement causes a module in Python 2.7 to use Python 3.0 rules for division instead (see above). In Python terms, the <code>/</code> operator represents ''true division'' (or simply ''division''), while the <code>//</code> operator represents ''floor division.'' Before version 3.0, the <code>/</code> operator represents ''classic division''.<ref name="pep0238"/> [[Rounding]] towards negative infinity, though a different method than in most languages, adds consistency to Python. For instance, this rounding implies that the equation {{code|class=nowrap|2=python|1=(a + b)//b == a//b + 1}} is always true. The rounding also implies that the equation {{code|class=nowrap|2=python|1=b*(a//b) + a%b == a}} is valid for both positive and negative values of <code>a</code>. As expected, the result of <code>a%b</code> lies in the [[half-open interval]] [0, ''b''), where <code>b</code> is a positive integer; however, maintaining the validity of the equation requires that the result must lie in the interval (''b'', 0] when <code>b</code> is negative.<ref name="AutoNT-62"/> Python provides a <code>round</code> function for rounding a float to the nearest integer. For [[Rounding#Tie-breaking|tie-breaking]], Python 3 uses the ''round to even'' method: <code>round(1.5)</code> and <code>round(2.5)</code> both produce <code>2</code>.<ref name="AutoNT-64"/> Python versions before 3 used the [[Rounding#Rounding away from zero|round-away-from-zero]] method: <code>round(0.5)</code> is <code>1.0</code>, and <code>round(-0.5)</code> is <code>−1.0</code>.<ref name="AutoNT-63"/> Python allows Boolean expressions that contain multiple equality relations to be consistent with general usage in mathematics. For example, the expression <code>a < b < c</code> tests whether <code>a</code> is less than <code>b</code> and <code>b</code> is less than <code>c</code>.<ref name="AutoNT-65"/> C-derived languages interpret this expression differently: in C, the expression would first evaluate <code>a < b</code>, resulting in 0 or 1, and that result would then be compared with <code>c</code>.<ref name="CPL"/> Python uses [[arbitrary-precision arithmetic]] for all integer operations. The <code>Decimal</code> type/class in the <code>decimal</code> module provides [[decimal floating point|decimal floating-point numbers]] to a pre-defined arbitrary precision with several rounding modes.<ref name="AutoNT-88"/> The <code>Fraction</code> class in the <code>fractions</code> module provides arbitrary precision for [[rational number]]s.<ref>{{cite web|title=What's New in Python 2.6 |url=https://docs.python.org/2.6/whatsnew/2.6.html|website=Python v2.6.9 documentation |date=Oct 29, 2013 |access-date=26 September 2015|archive-date=23 December 2019|archive-url=https://web.archive.org/web/20191223213856/https://docs.python.org/2.6/whatsnew/2.6.html|url-status=live}}</ref> Due to Python's extensive mathematics library and the third-party library [[NumPy]], the language is frequently used for scientific scripting in tasks such as numerical data processing and manipulation.<ref>{{Cite web|url=https://www.stat.washington.edu/~hoytak/blog/whypython.html|title=10 Reasons Python Rocks for Research (And a Few Reasons it Doesn't) – Hoyt Koepke|website=University of Washington Department of Statistics |access-date=3 February 2019|archive-date=31 May 2020|archive-url=https://web.archive.org/web/20200531211840/https://www.stat.washington.edu/~hoytak/blog/whypython.html|url-status=dead}}</ref><ref>{{Cite web|url=https://engineering.ucsb.edu/~shell/che210d/python.pdf|title=An introduction to Python for scientific computing|last=Shell|first=Scott|date=17 June 2014|access-date=3 February 2019|archive-date=4 February 2019|archive-url=https://web.archive.org/web/20190204014642/https://engineering.ucsb.edu/~shell/che210d/python.pdf|url-status=live}}</ref> ===Function syntax=== [[Function (computer programming)|Functions]] are created in Python by using the <code>def</code> keyword. A function is defined similarly to how it is called, by first providing the function name and then the required parameters. Here is an example of a function that prints its inputs: <syntaxhighlight lang="python3"> def printer(input1, input2="already there"): print(input1) print(input2) printer("hello") # Example output: # hello # already there </syntaxhighlight>To assign a default value to a function parameter in case no actual value is provided at run time, variable-definition syntax can be used inside the function header.
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)